Consider the following example:
#include <cstdio>
class object
{
public:
object()
{
printf("constructor
");
}
object(const object &)
{
printf("copy constructor
");
}
object(object &&)
{
printf("move constructor
");
}
};
static object create_object()
{
object a;
object b;
volatile int i = 1;
// With #if 0, object's copy constructor is called; otherwise, its move constructor.
#if 0
if (i)
return b; // moves because of the copy elision rules
else
return a; // moves because of the copy elision rules
#else
// Seems equivalent to the above, but behaves differently.
return i ? b : a; // copies (with g++ 4.7)
#endif
}
int main()
{
auto data(create_object());
return 0;
}
And consider this bit from the C++11 Working Draft, n3337.pdf, 12.8 [class.copy], point 32:
When the criteria for elision of a copy operation are met or would be met save for the fact that the source object is a function parameter, and the object to be copied is designated by an lvalue, overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue. If overload resolution fails, or if the type of the first parameter of the selected constructor is not an rvalue reference to the object’s type (possibly cv-qualified), overload resolution is performed again, considering the object as an lvalue. [Note: This two-stage overload resolution must be performed regardless of whether copy elision will occur. It determines the constructor to be called if elision is not performed, and the selected constructor must be accessible even if the call is elided. —end note ]
Thus, if we use #if 1
in the example, the move constructor is first tried when returning the object, and then the copy constructor. Since we have a move constructor, it is used instead of the copy constructor.
In the last return
statement in create_object()
however, we've observed that the move constructor is not used. Is or is this not a violation of the language rules? Does the language require that the move constructor is used in the last return
statement?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…