When you initialize another newly constructed object with a custom class type Object that has already been initialized, the copy constructor is automatically called. In other words, the copy constructor is called when the object of the class needs to be copied. The copy constructor is called when: (1) An object is passed into the function body as a value (2) An object is returned from the function as a value (3) An object needs to be initialized by another object. If a copy constructor is not explicitly declared in the class, the compiler will automatically generate a default copy constructor that completes the bit copy between the objects. A bit copy is also called a shallow copy.
Deep copy with shallow copy class Name{public:name (const char *_p) {len = strlen (_p); m_p = (char *) malloc (len + 1); strcpy (m_p, _p);} Name obj2 = obj1;//hand-written copy constructor for deep copy Name (const name& obj) {len = obj.len;m_p = (char *) malloc (len + 1); strcpy (M_p, O bj.m_p);} ~name () {if (m_p! = NULL) {free (m_p); m_p = Null;len = 0;}} Private:char *m_p;int len;protected:};void Obj_main () {Name obj1 ("ABCDEFG"); Name obj2 = obj1;//Default copy constructor provided by the C + + compiler}int Main () {obj_main (); System ("pause"); return 0;}
A shallow copy copies only the memory variables, that is, two variables store the same pointer variable, pointing to the same piece of memory space. The destruction of the OBJ2 is first, then the obj1.
This is a problem: When obj2 the memory release (such as: destruction), then the obj1 pointer is a wild pointer, there is a run error.
A deep copy is a copy of the content pointed to by the obj1, pointing to different memory spaces, respectively.
C + + deep copy and shallow copy