Home  >  Article  >  Backend Development  >  Why isn't the C 11 move constructor called when instantiating an object with another object?

Why isn't the C 11 move constructor called when instantiating an object with another object?

Linda Hamilton
Linda HamiltonOriginal
2024-11-05 08:20:02652browse

Why isn't the C  11 move constructor called when instantiating an object with another object?

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:

  • Return Statements: Non-volatile automatic objects with the same cv-unqualified type as the function return type can be constructed directly into the return value.
  • Throw Expressions: Non-volatile automatic objects whose scope does not extend beyond the innermost enclosing try-block can be constructed directly into the exception object.
  • Temporary Objects: Temporary objects that have not been bound to a reference can be constructed directly into objects with the same cv-unqualified type.
  • Exception Handlers: Exception declarations of an exception handler can be treated as aliases for the exception object, omitting the copy or move operation.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn