c++ - xvalue 和 prvalue 之间的一些区别

标签 c++ c++11 lifetime xvalue prvalue

我最近一直在仔细研究 C++ 类别。 lvalue 和 rvalue 之间的区别似乎很清楚,但是当谈到 prvalue 和 xvalue 时,我感到困惑。
给出下面的例子:

#include <iostream>
using std::cout;
using std::endl;
using std::move;
class Type {
public:
    int value;
    Type(const int &value=0) :value(value) {}
    Type(const Type &type) :value(type.value){}
    Type(Type &&type) noexcept :value(type.value) {}
    Type &operator= (const Type &type) {
        value = type.value;
        return *this;
    }
    Type &operator=(Type &&type) noexcept{
        value = type.value;
        return *this;
    }
};
Type foo1(const Type &value) {
    return Type(value);
}
Type &&foo2(const Type &value) {
    return Type(value);
}
int main() {
    Type bar1(123);
    cout << foo1(bar1).value << endl;
    cout << foo2(bar1).value << endl;
    Type bar2;
    bar2 = foo1(bar1);
    cout << bar2.value << endl;
    bar2 = foo2(bar1);
    cout << bar2.value << endl;
    return 0;
}
运行示例,控制台输入:
123
123
123
-858993460

谁能解释为什么它在最后一个输出中给出了意想不到的值?
这个例子展示了 xvalue 的什么特征?

最佳答案

foo2正在返回绑定(bind)到临时的引用,该引用立即被销毁;它总是返回一个悬空的 reference .

a temporary bound to a return value of a function in a return statement is not extended: it is destroyed immediately at the end of the return expression. Such function always returns a dangling reference.


取消引用返回的引用,如 foo2(bar1).valuebar2 = foo2(bar1);导致UB;一切皆有可能。
另一方面,foo1没有这样的问题。返回值从临时对象中移出。

关于c++ - xvalue 和 prvalue 之间的一些区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64392338/

相关文章:

rust - 什么是 impl Trait + 'lifetime

c++ - 指向指针算术的指针

c++ - 重载算术中的 move 语义和传递右值引用

c++ - 有没有办法限制 STL Map 的大小?

c++ - 转发声明枚举类不起作用

c++ - 如何避免在不适当的线程上下文中破坏 shared_ptr?

rust - 如何将临时字符串转换为 &str?

php - 通过 id 检查 session 是否存在,而不更新 session 的生命周期

c++ - 如何初始化属于 struct typedef 一部分的数组?

c++ - 如何在libgit2中打印差异文件?