First, the nature of the replication constructor is still the constructor, but it is usually called during replication initialization (direct initialization may also be called, which will be mentioned later ).
Definition: The copy constructor only has a single parameter referenced by this class Object (commonly used const modifier ).
class Test(){public: Test(const Test& t) {}};
String null_book = "9-999-99999-9"; // copy the initialization string book (10, 'A'); // directly initialize string empty_copy = string (); // copy the initialization string empty_direct; 1 // directly initialize
From the above example, we can see that the most direct difference between replication initialization and direct Initialization is whether "=" is used. What is the actual process?
When creating null_book, the compiler calls the string constructor that accepts the C-style string parameters, creates a temporary object, and then uses the copy constructor to initialize null_book as a copy of the temporary object.
In the preceding example, you can directly call the corresponding constructor through direct initialization. The exception is string empty_direct2 (empty_direct). This is a direct initialization, but the copy constructor is called, generate a copy directly.
The compiler usually performs optimization, for example
string word(”abcd“);string word = "abcd";
The compiler has noticed that the effect of direct Initialization is the same as that of copy initialization, so the latter is optimized to the former.
However, there is only a difference between direct initialization and replication initialization in terms of low-level optimization. However,
- The replication type is not supported.
- Use non-explicit Constructor
They have essential differences:
ifstream file1("filename");ifstream file2 = "filename";
Obviously, the latter is incorrect. "=" means the replication is initialized, while ifstream does not allow replication.
Vector <int> V1 (42); // okvector <int> v2 = 42; // The replication constructor of error vector is private.
Note that the former is directly initialized, but the process is:
Use intDefaultThe constructor creates a temporary value to initialize the SVEC, and then copies the temporary value to each element of the SVEC using the copy constructor. It seems that the previous step is much more than one, so
As a general rule, unless you want to use the default initial values of container elements, a more effective way is to allocate an empty container and add the values of known elements to the container.
The copy constructor is used:
- Initialize (explicitly and implicitly) an object with another object.
- Returns a Copied object.
- Passed as a real parameter to the function (the object is copied in this process ).
- Sequential container Initialization
- Initialize array elements based on the element initialization list