class elem
{
public:
elem()
{
}
elem(elem &)
{
cout << 222222 << endl;
}
elem(elem &&)
{
cout << 111111 << endl;
}
};
elem fun()
{
elem e;
elem f(e);
return e;
}
void main()
{
fun();
}
Output:
22222
11111
My confusion:
As I return an lvalue in fun
, why is fun
not calling the copy constructor but move constructor? When does 'e' change to a rvalue in the return expression?
Note: I have turned off the copy elision.
If you declare a local variable within a function and return it out of the function, it is an rvalue. Also there is a binding rule which says... “The r-value reference in move constructor is preferred over const l-value reference in copy constructor — these are the rules for binding expression values to references. If move constructor is not available, the second preference — copy constructor — is chosen”. As from @Olef's comment, see also, Automatic move from local variables and parameters .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.