[英]c++: function lvalue or rvalue
I just started learning about rvalue references in c++11 by reading this page , but I got stuck into the very first page. 我刚开始通过阅读本页来了解c ++ 11中的右值引用,但我陷入了第一页。 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()
an lvalue? foo()
是一个左值? is it because foo()
returns int&
which is basically an lvalue? foo()
返回int&
它基本上是一个左值? foobar()
an rvalue? foobar()
是右值? is it because foobar()
returns int
? foobar()
返回int
? L-Values are locations, R-Values are actual values. L值是位置,R值是实际值。
So: 所以:
foo()
returns a reference( int&
), that makes it an lvalue itself. foo()
返回一个引用( int&
),这使得它本身就是一个左值。 foobar()
is an rvalue because foobar()
returns int
. foobar()
是一个右值,因为foobar()
返回int
。 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:
我对R值引用感到兴奋的原因是移动语义,例如:
BigClass my_function (const int& val, const OtherClass & valb);
BigClass x;
x = my_function(5, other_class_instance);
In that example, x is destroyed, then the return of my_function is copied into x with a copy constructor. 在该示例中,x被销毁,然后使用复制构造函数将my_function的返回复制到x中。 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);
which means that now my_function
has side effects, plus it isn't as plain to read. 这意味着现在
my_function
有副作用,而且它不是那么简单。 Now, with C++11, we can instead write: 现在,使用C ++ 11,我们可以改为:
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. 并使其运行与第二个例子一样有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.