C ++:函数左值或右值 [英] c++: function lvalue or rvalue
问题描述
我刚刚通过阅读此页面,开始学习c ++ 11中的右值引用。 ,但我陷入了第一页。这是我从该页面获取的代码。
I just started learning about rvalue references in c++11 by reading this page, but I got stuck into the very first page. Here is the code I took from that page.
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
吗? - 通常,为什么您会在乎函数是否为右值?我想,如果我读完该文章的其余部分,就会得到答案。
- why is
foo()
an lvalue? is it becausefoo()
returnsint&
which is basically an lvalue? - why is
foobar()
an rvalue? is it becausefoobar()
returnsint
? - In general, why would you care if a function is an rvalue or not? I think if I read the rest of that article, I'll get my answer to this.
推荐答案
L值是位置,R值是实际值。
L-Values are locations, R-Values are actual values.
所以:
- 因为
foo()
返回一个引用(int&
),这使其本身成为左值。 - 正确。
foobar()
是一个右值,因为foobar()
返回int
。 - 我们并不在乎函数是否为R值。令我们兴奋的是R值引用。
- since
foo()
returns a reference(int&
), that makes it an lvalue itself. - Correct.
foobar()
is an rvalue becausefoobar()
returnsint
. - We don't care that much if a function is an R-Value or not. What we are getting excited about is R-Value references.
您指向的文章很有趣,我没有考虑过转发或在工厂使用之前。我对R值引用感到兴奋的原因是移动语义,例如:
The article you pointed to is interesting and I had not considered forwarding or the use in factories before. The reason I was excited about R-Value references was the move semantics, such as this:
BigClass my_function (const int& val, const OtherClass & valb);
BigClass x;
x = my_function(5, other_class_instance);
在该示例中,x被销毁,然后使用复制构造函数将my_function的返回值复制到x中。要在历史上解决该问题,您可以这样写:
In that example, x is destroyed, then the return of my_function is copied into x with a copy constructor. To get around that historically, you would write:
void my_function (BigClass *ret, const int& val, const OtherClass & valb);
BigClass x;
my_function(&x, 5, other_class_instance);
这意味着现在 my_function
具有副作用,而且阅读起来不那么简单。现在,使用C ++ 11,我们可以改为:
which means that now my_function
has side effects, plus it isn't as plain to read. Now, with C++11, we can instead write:
BigClass & my_function (const int& val, const OtherClass & valb);
BigClass x;
x = my_function(5, other_class_instance);
使其运行效率与第二个示例一样。
And have it operate as efficiently as the second example.
这篇关于C ++:函数左值或右值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!