簡體   English   中英

c ++:函數左值或右值

[英]c++: function lvalue or rvalue

我剛開始通過閱讀本頁來了解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
  1. 為什么foo()是一個左值? 是因為foo()返回int&它基本上是一個左值?
  2. 為什么foobar()是右值? 是因為foobar()返回int
  3. 一般來說,為什么你會關心函數是否是右值? 我想如果我讀完那篇文章的其余部分,我會得到答案。

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

並使其運行與第二個例子一樣有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM