C + + Copy constructors

Source: Internet
Author: User

A copy constructor is a special constructor that is defined as a reference to the first parameter of this type, or as a constant reference, with no other parameters or other parameters as default values, such as the following function:

1     X::X (const x&);           2     int a=1);       3     int a=1int b=2);  

So when do I call the copy constructor?

1. Object passed in as value pass in parameter

1 int Main ()   2 {  3  cexample Test (1);   4  // Incoming Object   5 Fun (test);   6   7  return 0 ;   8 }  

The process of calling fun is as follows:

(1) When the test object is passed into the function, create a TEMP variable temp

(2) Call the copy constructor to assign the value of test to a temporary variable, similar to Cexample temp (test)

(3) After the fun call is over, analyze the temp

2. The object is returned from the function in the way value is passed

1 cexample Fun ()   2 {  3  cexample object (0);   4  return object;   5 }  

When the fun function executes to return, the steps are as follows:

(1) Create a temp variable first

(2) Call the copy constructor to assign the object to temp, similar to Cexample temp (object)

(3) function execution to the last, first, the local variable object

(4) After the fun is done, analyze the Temp

About shallow copies and deep copies:

The so-called shallow copy, refers to when the object is copied, only the members of the object is simply assigned , the default copy constructor is also a shallow copy of the execution. In most cases a "shallow copy" has worked well, but once the object has a dynamic member, a shallow copy can be problematic. The

Deep copy is applicable to the existence of dynamic members of the object, in the case of "deep copy", for the dynamic members of the object can not simply assign value, but should be re -assigned to the space, or as a shallow copy of the same memory space will be freed 2 times, This is wrong.

C + + Copy constructors

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.