我刚刚开始通过阅读 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
- 为什么
foo()
是左值?是因为foo()
返回的int&
基本上是一个左值吗? - 为什么
foobar()
是右值?是因为foobar()
返回int
吗? - 一般来说,您为什么要关心函数是否为右值?我想如果我读完那篇文章的其余部分,我就会得到我的答案。
最佳答案
L 值是位置,R 值是可存储值(即,可以分配的值:例如, namespace 不可可分配;感谢@ Maggyero 的编辑建议)。
所以:
- 由于
foo()
返回一个引用 (int&
),因此它本身就是一个左值。 - 正确。
foobar()
是右值,因为foobar()
返回int
。 - 我们不太关心函数是否为 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/