2012-12-13 56 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); 

並且讓它的操作和第二個例子一樣高效。