2012-12-13 42 views
2

我刚刚开始通过阅读this page了解C++ 11中的右值引用,但我陷入了第一页。这是我从该页面获取的代码。C++:函数左值或右值

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. 一般来说,如果一个函数是一个右值,为什么要关心?我想如果我阅读那篇文章的其余部分,我会得到我的答案。

回答

4

L-值是位置,R-值是实际值。

所以:

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

并且让它的操作和第二个例子一样高效。