简体   繁体   English

返回表达式是否被视为 c++ 中的临时 object?

[英]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.

相关问题 绑定到参数和返回值const引用的C ++临时对象 - C++ temporary object bound to argument and return value const references C ++:通过引用将std :: vector &lt;&gt;成员返回给临时对象 - C++: return a std::vector<> member, by reference, to a temporary object c ++重载+运算符不返回临时对象,为什么? - c++ overloaded + operator does not return a temporary object , why? C ++错误 - “成员初始化表达式列表被视为复合表达式” - C++ error - “member initializer expression list treated as compound expression” C++中临时对象的销毁 - Destruction of a temporary object in C++ c++ 临时 object 问题 - c++ Temporary object question 是否在?:expression中创建的C ++临时对象的生命周期是通过将其绑定到本地const引用来扩展的? - Is the lifetime of a C++ temporary object created in ?: expression extended by binding it to a local const reference? 以临时对象作为参数的C ++对象构造函数 - C++ Object Constructor with Temporary Object as Argument 返回临时对象是否在C ++中创建临时对象? - Does returning a temporary object create a temporary object in C++? 在C ++中可以将在堆上创建的对象视为“堆栈中”吗? - Could be an object created on the heap treated as 'being on stack' in C++?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM