C++ 右值和移动

标签 c++ c++11

请帮助理解下面的内容

class Demo {};
    Demo && fun() {
        Demo d;
        cout << "Addres of d in fun " << &d << endl;
        return move(d);
    }
int main()
{
    Demo && d = fun() 
}

这是返回对象的正确方法吗??

最佳答案

返回对局部变量的引用是未定义的行为,所以不,这段代码不正确。

返回对象的正确方法是返回纯右值:

Demo fu(n) {
  Demo d;
  return d;   // "move(d)" is implied
}

Demo && d = fun();  // OK, reference binds to temporary and extends its lifetime

关于C++ 右值和移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31838467/

相关文章:

c++ - constexpr static std::array<const char *,5> 无法使用 MSVC2013 进行编译

c++ - 在 using 语句中指定类名有什么作用?

c++ - 如何集成开源 C 程序而不是通过系统调用调用其可执行文件?

c++ - 仅通过指针转换创建可互换的类类型,而无需分配任何新对象?

c++ - 函数返回的 RVO 和右值如何工作?

C++ 使用 std::function 从命名空间中返回一个函数

javascript - 数据通过 websocketpp 返回为 json,但通过 messagepack 返回为 Blob

c++ - UE4 类运算符 bool() 重载

c++ - 为 iOS 编译 OpenCV 失败

c++ - 从 C++ 调用 COM dll, "Class Not Registered"