所以,我有以下类(class):
class Foo {
public:
Bar &&bar() {
return std::move(_bar);
}
private:
Bar _bar;
}
我知道在以下上下文中使用此类是有效的:
Bar bar;
{
Foo foo;
bar = foo.bar(); // bar is move-assigned, as foo is still in scope
}
现在,我想知道的情况是:如果我直接从方法返回 bar 而不事先存储它会发生什么:
Bar testFunc() {
Foo foo;
return foo.bar();
}
Bar test = testFunc();
// is test now valid?
我认为这在理论上应该没问题,因为 testFunc
返回一个值,该值是在 foo
被销毁之前从右值构造的 - 但如果编译器应用返回值优化?
我想我有点困惑这究竟是如何工作的......
最佳答案
is test now valid?
只要移出的对象未被访问,代码就应该有效。
but is this still the case if the compiler applies return-value-optimization?
Bar testFunc() {
Foo foo; // Bar is constructed here
return foo.bar(); // prvalue is move-constructed and copy elided
}
Bar test = testFunc(); // default ctor + move ctor (one copy elision)
总共执行了一个拷贝省略。
将成员移出似乎是一种代码味道。不了解具体用法很难判断,但可能是:
Bar make_bar(const Foo& foo) {
Bar bar;
// init bar as needed
return bar;
}
这样两个调用都会产生 RVO。
关于c++ - 返回临时的右值作为值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50696961/