Copy Constructor Invoked by Direct Initialization
In the provided code snippet, you might expect the copy constructor to be invoked when assigning A(5) to a. However, the code never calls the copy constructor. This behavior is not a result of compiler optimization but rather a documented feature of C .
When you initialize an object using direct initialization (A a = A(5);), the compiler performs copy elision. This optimization removes the unnecessary construction of a temporary object followed by the copy of that object to the initialized variable. Instead, the initialized variable is directly initialized with the argument to the constructor.
This behavior is documented in the C standard (§12.8.15, pg. 211), which states that direct initialization is equivalent to constructing the object in-place using the arguments to the constructor:
T x; // Default initialization T x = y; // Direct initialization
In this case, a is initialized directly with the arguments to the A constructor, bypassing the copy constructor. To force the compiler to invoke the copy constructor, you would need to default construct a first:
A a; // A is now a fully constructed object, // so it can't call constructors again: a = A(5);
This ensures that the copy constructor is called when a is assigned the value of A(5).
The above is the detailed content of Why Isn't the Copy Constructor Called During Direct Initialization in C ?. For more information, please follow other related articles on the PHP Chinese website!