C ++ shallow copy and deep copy

Source: Internet
Author: User

What is shortest copy and deep copy? A shallow copy is actually a copy object instead of an object referenced by it. That is, all the variables of the object to be copied contain the values of the object to be copied, and the reference of the object to other objects still points to the original object. For example, char ori [] = "hello"; char * copy = ori; here, the value assignment operation of copy is shallow copy; the value of copy is equal to the value of ori, in addition, copy points to the same object and ori, but the copy and ori are not completely equal, and the ori is not completely copied. Char ori [] = "hello"; char * copy = new char []; copy = ori; deep copy Copies all the objects referenced by the objects to be copied, that is, the Copied object contains the same value of the Copied object, but the referenced object is a new object that has been copied, instead of the object referred to by the Copied object. In fact, it is a common problem in OC. OC retains keywords such as obtain, assign, and copy to emphasize light copy and deep copy, these are not specifically emphasized in the C ++ language. Next we will analyze the code below: class A {char * a; public: A () {a = (char *) malloc (10 );}~ A () {if (NULL! = A) free (a) ;}}; void process () {A, B; a = B ;} this section of code is a typical problem of understanding Deep copy and shallow copy. C ++ uses the shortest copy of the execution class attribute by default. Here, object a only copies object B, that is, it uses the memory allocated by a shortest copy, the memory allocated by B is not released. Therefore, memory leakage occurs.

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.