Why Copy Constructor is Bypassed When Assigning a New Value to an Existing Object
In the provided code snippet, an object a is initialized with the value 5. The standard A constructor is invoked as expected. However, contrary to assumptions, the copy constructor is not called when assigning the newly constructed object.
This behavior is neither the result of compiler optimization nor an omission in the language specification. It is explicitly documented in the C standard (§12.8.15, pg. 211). The standard states that "it is completely acceptable" for the following assignments to be semantically equivalent:
T = x; T(x);
It logically follows that a redundant assignment like T(T(x)) can be removed from the code optimization. Therefore, the compiler automatically invokes the default constructor to initialize a and then directly assigns the newly constructed object.
To force the copy constructor to be invoked, one needs to explicitly default-construct a before assigning:
A a; // Default-construct 'a' // Copy constructor will be called to // copy data from the newly constructed object. a = A(5);
The above is the detailed content of Why Isn't the Copy Constructor Called When Assigning to an Existing Object in C ?. For more information, please follow other related articles on the PHP Chinese website!