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 日

18K+ 次檢視

開始你的職業生涯

完成課程獲取認證

開始學習
廣告