c ++:函数左值或右值

ami*_*far 5 c++ rvalue lvalue c++11

我刚开始通过阅读本页来了解c ++ 11中的右值引用,但我陷入了第一页.这是我从该页面获取的代码.

  int& foo();
  foo() = 42; // ok, foo() is an lvalue
  int* p1 = &foo(); // ok, foo() is an lvalue

  int foobar();
  j = foobar(); // ok, foobar() is an rvalue
  int* p2 = &foobar(); // error, cannot take the address of an rvalue
Run Code Online (Sandbox Code Playgroud)
  1. 为什么是foo()左值?是因为foo()回报int&基本上是一个左值?
  2. 为什么是foobar()左值?是因为foobar()回归int
  3. 一般来说,为什么你会关心函数是否是右值?我想如果我读完那篇文章的其余部分,我会得到答案.

Jos*_*oyd 11

L值是位置,R值是实际值.

所以:

  1. 因为foo()返回一个引用(int&),这使它成为一个左值.
  2. 正确.foobar()是一个右值因为foobar()回报int.
  3. 如果函数是否是R值,我们并不在意.我们感到兴奋的是R值参考.

您指出的文章很有趣,我以前没有考虑转发或在工厂中使用.我对R值引用感到兴奋的原因是移动语义,例如:

BigClass my_function (const int& val, const OtherClass & valb);

BigClass x;
x = my_function(5, other_class_instance);
Run Code Online (Sandbox Code Playgroud)

在该示例中,x被销毁,然后使用复制构造函数将my_function的返回复制到x中.为了在历史上解决这个问题,你会写:

void my_function (BigClass *ret, const int& val, const OtherClass & valb);

BigClass x;
my_function(&x, 5, other_class_instance);
Run Code Online (Sandbox Code Playgroud)

这意味着现在my_function有副作用,而且阅读并不简单.现在,使用C++ 11,我们可以改为:

BigClass & my_function (const int& val, const OtherClass & valb);

BigClass x;
x = my_function(5, other_class_instance);
Run Code Online (Sandbox Code Playgroud)

并使其运行与第二个例子一样有效.

  • “R 值是实际值”更准确地说,R 值是“可存储”值。有些值无法在 C++ 中赋值,因此不是 R 值,例如类型、命名空间。 (2认同)