跳至內容

移動賦值運算符

維基百科,自由的百科全書

C++語言中,移動賦值運算符(move assignment operator)=用於把一個臨時對象轉移給一個已存在對象並可以運算符重載。類似於複製賦值運算符,移動賦值運算符也是特殊成員函數。這是從C++11開始引入的概念。

在沒有定義拷貝構造函數、拷貝賦值運算符、析構函數和移動構造函數時,編譯器會自動生成移動賦值運算符。[1]在實踐中,這個特性非常有用 —— 有些資源只應該被移動而不應該被拷貝,如mutexsocket

移動賦值運算符的操作數是右值引用類型的(T&&),其中T是定義了移動賦值運算符的對象本身。

移動賦值運算符不同於移動構造函數。前者是賦值給一個已存在的對象。後者是創建一個新對象。二者完成後,操作數對象不復存在。

移動賦值運算符的重載[編輯]

重載移動賦值運算符時,運算符函數的類型必須為:[1]

T& operator=(T&& data)

一般應滿足:

  • 檢查不會把對象「移動」給自身,這麼做無意義。
  • 當前對象的數據要先釋放掉。
  • 被移動掉數據的對象必須用nullptr賦給其數據。
  • 運算符必須返回"*this"的引用。

下例為一個簡單字符串移動賦值運算符的重載:[2]

class String {
 public:
  String& operator=(String&& other) noexcept {
    // If we're not trying to move the object into itself...
    if (this != &other) {
      delete[] this->data_;  // Free this string's original data.
      this->data_ = other.data_;  // Copy the other string's data pointer into this string.
      other.data_ = nullptr;  // Finally, reset the other string's data pointer.
    }
    return *this;
  }

 private:
  char* data_;
};

參考文獻[編輯]

  1. ^ 1.0 1.1 Move assignment operator - cppreference.com. en.cppreference.com. [2016-02-23]. (原始內容存檔於2020-11-12). 
  2. ^ Move Constructors and Move Assignment Operators (C++). msdn.microsoft.com. [2016-02-23]. (原始內容存檔於2017-07-29).