我正在阅读 Stroustrup 的教科书以了解右值和移动构造函数的概念:
an rvalue is – to a first approximation – a value that you can’t assign to, such as an integer returned by a function call, and an rvalue reference is a reference to something that nobody else can assign to. The res local variable in operator+() for Vectors is an example.
上面引用的代码如下所列。
问题:局部变量 res
可以合法地出现在赋值的左侧,例如 res=nullptr
。为什么它被视为右值呢?
Vector operator+(const Vector& a, const Vector& b) {
if (a.size()!=b.size()) throw Vector_size_mismatch{};
Vector res(a.size());
for (int i=0; i!=a.size(); ++i) res[i]=a[i]+b[i];
return res;
}
最佳答案
不,局部变量不是右值。在您的示例中,右值是函数返回的临时对象,它是 res 的拷贝(尽管可以省略复制构造函数或移动构造函数的调用)。
res
本身是函数中的左值。
关于c++ - C++ 中的局部变量是右值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57027477/