C 11 Move Constructor Not Called, Default Constructor Preferred
Question:
In C 11, when instantiating an object via another object, why might the move constructor not be called when it should be?
Answer:
Upon instantiation, the compiler may occasionally apply a technique known as copy elision. Copy elision allows the direct construction of a temporary object into the target it would be copied or moved into, bypassing the copy or move constructor/destructor pair.
The standard allows copy elision in the following circumstances:
In the given example, when instantiating z with X("test"), copy elision occurs because it is considered a temporary object that has not been bound to a reference. Consequently, it is constructed directly into z, bypassing the move constructor and constructing z using the default constructor instead.
Explicitly calling move(X("test")) prevents copy elision and forces the use of the move constructor, as observed in the modified output.
The above is the detailed content of Why isn't the C 11 move constructor called when instantiating an object with another object?. For more information, please follow other related articles on the PHP Chinese website!