c++ - 返回临时的右值作为值

标签 c++ rvalue rvo

所以,我有以下类(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/

相关文章:

c++ - 关于左值到右值的转换,什么时候需要?

c++ - 为什么不能在函数之间直接传递右值引用参数?

C++11 昂贵的临时右值

c++ - 如何在 C++11 中初始化 uint64_t

c++ - 替换txt文件中的行c++

c++ - 将右值引用传递给右值引用参数时发生错误

c++ - 为什么在返回参数时不允许 RVO?

c++ - 包含字符串 : what really happens when it's returned from a function? 的类

c++ - 命令提示符可以显示unicode字符吗?

c++ - 模板中的第二阶段编译