C + + deep copy and shallow copy

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.