1. Copy constructor function
If the first parameter of a constructor is a reference to its own class type, and any additional arguments have default values, this constructor is a copy constructor.
C (const C &);//The argument is usually a const reference
The copy constructor occurs under the following conditions:
- used when copying initialization (= define variable).
- Passes an object as an argument to a parameter of a non-reference type.
- Returns an object from a function that returns a type that is not a reference type.
- Initializes an element in an array or a member of an aggregation class with a list of curly braces.
The parameter of the copy constructor must be a reference type, because if it is not a reference, the copy constructor is copied when it is called, and the copy constructor constructor is called, so an infinite loop is required to copy its arguments.
If we do not define a copy constructor for the class, the compiler will automatically synthesize a copy constructor.
(1) Copy initialization
Direct initialization is the requirement that the compiler use normal function matching to select the constructor that best matches the arguments we provide:
String S1 (, ' C ');
String S2 (S1);
Copy initialization requires the compiler to copy the right operand to the object being created (sometimes requiring a type conversion):
String s3=s1;
String s4= "abc";
String s5=string (+, ' C ');
Copy initialization is usually done using a copy constructor.
If you need type conversions during copy initialization, be aware that using explicit's constructor transforms only with direct initialization:
VECTOR<INT>V1 (10);//Direct initialization
vector<int>v2=10;//error, the constructor of the size parameter is accepted when explicit, cannot type converted after copy initialization
Similarly
void f (vector<int>);
f (10);//Error
F (vector<int> (10)); correct,//construct a temporary vector directly
C + + Copy control