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)
foo()左值?是因为foo()回报int&基本上是一个左值?foobar()左值?是因为foobar()回归int?Jos*_*oyd 11
L值是位置,R值是实际值.
所以:
foo()返回一个引用(int&),这使它成为一个左值.foobar()是一个右值因为foobar()回报int.您指出的文章很有趣,我以前没有考虑转发或在工厂中使用.我对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)
并使其运行与第二个例子一样有效.