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