Home > Article > Backend Development > Why Does the Implicit Move Rule Prefer a Copy Constructor Over a Move Constructor When the Move Constructor is Unavailable?
Returning a Class Object by Value with Implicit Move Rule
When returning an object of a class by value from a function, the implicit move rule comes into play. This rule determines which constructor to use to initialize the returned object. Typically, the move constructor is preferred if the object is considered an xvalue (an expression that can be moved from).
In your Example 1, the variable i declared in the Some_thing() function is an xvalue because it is declared in a local scope and is considered move-eligible. Therefore, the move constructor test(test&& s) is invoked, as shown in the output.
However, in Example 2, you removed the move constructor and modified the copy constructor to be test(test& z). This change resulted in the output showing the call to the copy constructor test(test& z) instead of the move constructor, which was expected due to the implicit move rule.
This seemingly contradictory behavior occurs because i is still considered an xvalue, but the compiler is now also considering the "regular" copy constructor as viable. The implicit move rule first attempts to use the move constructor, but since there isn't one, it proceeds to use the copy constructor.
To explicitly enforce the use of a move constructor, you can delete the copy constructor, as shown in Example 3. This prevents the compiler from considering the copy constructor as an option, and the move constructor will be used even if it is marked as const (which normally prevents moving).
Example 4 demonstrates that a const object can still be moved from if the move constructor is available and the move operation is noexcept. In this case, the temporary object created during the initialization of u is moved to r, resulting in the call to the move constructor.
The above is the detailed content of Why Does the Implicit Move Rule Prefer a Copy Constructor Over a Move Constructor When the Move Constructor is Unavailable?. For more information, please follow other related articles on the PHP Chinese website!