[英]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
foo()
是一個左值? 是因為foo()
返回int&
它基本上是一個左值? foobar()
是右值? 是因為foobar()
返回int
? 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);
在該示例中,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.