[英]Is the return expression treated as a temporary object in c++?
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: Output:
22222
11111
My confusion:我的困惑:
As I return an lvalue in fun
, why is fun
not calling the copy constructor but move constructor?当我在
fun
返回一个左值时,为什么fun
不调用复制构造函数而是移动构造函数? When does 'e' change to a rvalue in the return expression? 'e' 什么时候在返回表达式中变为右值?
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.如果您在 function 中声明一个局部变量并将其从 function 中返回,则它是一个右值。 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.
还有一条绑定规则说……“移动构造函数中的右值引用优于复制构造函数中的 const 左值引用——这些是将表达式值绑定到引用的规则。 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 .
正如@Olef 的评论,另请参见Automatic move from local variables and parameters 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.