求 C++ 中雙地址運算子 (&&) 是什麼?


&& 是 C++11 標準中定義的一個新的引用運算子。int&& a 表示“a”是一個右值引用。&& 通常用於宣告函式的一個引數。它只採用一個右值表示式。

簡單來說,右值是沒有記憶體地址的值。例如,數字 6 和字元 'v' 都屬於右值。int a,a 是左值,但是 (a+2) 是右值。

 示例

void foo(int&& a)
{
   //Some magical code...
}
int main()
{
   int b;
   foo(b);       //Error. An rValue reference cannot be pointed to a lValue.
   foo(5);       //Compiles with no error.
   foo(b+3);     //Compiles with no error.
   int&& c = b;  //Error. An rValue reference cannot be pointed to a lValue.
   int&& d = 5;  //Compiles with no error.
}

可以在 http://blogs.msdn.com/b/vcblog/archive/2009/02/03/rvalue-references-c-0x-features-in-vc10-part-2.aspx 閱讀更多有關右值和該運算子的資訊。


更新日期:2020 年 2 月 11 日

1.8 萬+ 檢視次數

開啟你的 職業 生涯

透過完成課程獲得認證

開始
廣告