c++ - 按值返回与右值引用

标签 c++ reference rvalue return-by-reference return-by-value

question about returning temporaries 上回复后我注意到第二个回复略有不同。

它不是按值返回,而是按右值引用返回。 您能解释一下这些方法之间的区别以及它们的风险所在吗?

struct Bar
    {
    Bar& doThings() & {return *this;}

     // Returning rvalue reference
    Bar&& doThings() &&    {return std::move(*this);}

     // Alternative: Returning by value
    //Bar doThings() && {return std::move(*this);}

    std::unique_ptr<int> m_content; // A non-copyable type
    };

最佳答案

一个主要区别是,如果返回右值引用,当返回值绑定(bind)到引用时,临时对象的生命周期不会延长。

例如,

Bar&& rb = Bar{}.doThings();
use(rb); // not safe if returning rvalue reference, while safe if returning by value

关于c++ - 按值返回与右值引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51220975/

相关文章:

c++ - "main"函数可以用 "noexcept"说明符声明吗?

c++ - "Node<T*> *first"和 "Node<T> *first"有什么区别?

c# - 您可以忽略特定版本的强命名引用吗?

c++ - 将函数声明为 BigStruct&& foo(...) 是一种好习惯吗?

c++ - Mac OS X 10.7.4 和 FreeBSD 9.0 上没有右值引用

c++ - vector 的小字符串优化?

php - 函数内部的静态变量不能保存对单例的引用

c++ - 保护私有(private)成员通过引用返回,避免意外重新分配

c++ - 纯右值与 C++17 中的临时值相同吗

c++ - C++11 之前的可变参数模板