C++ Primer 筆記——理解std::move

來源:互聯網
上載者:User

標籤:string   bsp   執行個體化   typename   color   筆記   過程   資料   使用   

標準庫move函數是使用右值引用的模板的一個很好的例子。標準庫是這樣定義std::move的:

template <typename T>typename remove_reference<T>::type&& move(T&& t){    return static_cast<typename remove_reference<T>::type&&>(t);}

 

我們考慮如下代碼的工作過程:

std::string s1("hi"), s2;s2 = std::move(string("hi"));    // 正確,從一個右值移動資料s2 = std::move(s1);                // 正確,但是在賦值之後,s1的值是不確定的


在第一個賦值中,實參是string類型的右值,因此過程為:

  • 推斷T的類型為 string
  • remove_reference<string> 的 type 成員是 string
  • move 傳回型別是 string&&
  • move 的函數參數t的類型為 string&&

因此,這個調用執行個體化 move<string>,即函數

string&& move(string &&t)


在第二個賦值中,實參是一個左值,因此:

  • 推斷T的類型為 string&
  • remove_reference<string&> 的 type 成員是 string
  • move 傳回型別是 string&&
  • move 的函數參數t的類型為 string& &&,會摺疊成 string&

因此,這個調用執行個體化 move<string&>,即

string&& move(string &t)

 

  通常情況下,static_cast 只能用於其他合法的類型轉換。但是有一條針對右值的特許規則:雖然不能隱式的將一個左值轉換成右值引用,但我們可以用static_cast顯示的將一個左值轉換為一個右值。

 

C++ Primer 筆記——理解std::move

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.