c++:函数左值或右值

标签 c++ c++11 lvalue rvalue

我刚刚开始通过阅读 this page 了解 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
  1. 为什么 foo() 是左值?是因为 foo() 返回的 int& 基本上是一个左值吗?
  2. 为什么 foobar() 是右值?是因为 foobar() 返回 int 吗?
  3. 一般来说,您为什么要关心函数是否为右值?我想如果我读完那篇文章的其余部分,我就会得到我的答案。

最佳答案

L 值是位置,R 值是可存储值(即,可以分配的值:例如, namespace 不可可分配;感谢@ Maggyero 的编辑建议)。

所以:

  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);

在该示例中,x 被销毁,然后使用复制构造函数将 my_function 的返回值复制到 x 中。要从历史上解决这个问题,您可以这样写:

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

BigClass x;
my_function(&x, 5, other_class_instance);

这意味着现在 my_function 有副作用,而且它不那么容易阅读。现在,使用 C++11,我们可以改写:

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

BigClass x;
x = my_function(5, other_class_instance);

并让它像第二个示例一样高效地运行。

关于c++:函数左值或右值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13854518/

相关文章:

c++ - 奇怪的 C++ 内存使用

C++ 变量头作用域

c++ - 使用 boost::phoenix 适配 BOOST_CHECK 宏

c++ - 可以取地址的变量是左值,这是真的吗?

C++ 在初始化器中指定数组索引,如 C

c++ - 如果没有 '&&' 的语句有效?

C++11:decltype((x)) 和 decltype((x+1)) 的类型不同?

c++ - move 语义和虚拟方法

c++ - 在访问引用类型的成员时总是使用左值是什么情况?

c - C 中两个动态增长数组的指针复制