在 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/