c++ - C++ 中的局部变量是右值吗?

标签 c++ rvalue

我正在阅读 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/

相关文章:

c++ - 在数值模拟中使用 std::valarray

c++ - 虚函数默认参数行为

c++ - 用于通用引用的左值/右值 -nes 编码

c++ - 需要一些关于 r 值概念的帮助

C++使用递归查找Vector中非零的数量

c++ - 当解引用运算符 (*) 被重载时,*this 的使用会受到影响吗?

c++ - "Warning: corrupt .drectve at end of def file"是什么意思?

c++ - 右值的成员访问运算符应该是一个 xvalue 吗?

c++ - 接受左值和右值参数的函数

c++ - 为什么 T 在这里不推导为 int&&