gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:11:11 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com