【发布时间】:2021-01-31 03:55:32
【问题描述】:
我最近一直在仔细研究 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返回对已销毁的局部变量的引用。所以参考是悬空的。这与prvalues vsxvalues 没有任何关系。
标签: c++ c++11 lifetime xvalue prvalue