Move assignment operator Tutorial
  • go - Tutorial
  • - Css
  • - W3css
  • go - Useful Resources
  • Go - Ebook Download

  • Move assignment operator

    In the C++ programming language, the move assignment operator = is used for transferring a temporary object to an existing object. The move assignment operator, like most C++ operators, can be overloaded. Like the copy assignment operator it is a special member function.

    If the move assignment operator is not explicitly defined, the compiler generates an implicit move assignment operator C++11 and newer provided that copy/move constructors, copy assignment operator or destructors have not been declared. The parameter of a move assignment operator is an rvalue reference T&& to type T, where T is the object that defines the move assignment operator. The move assignment operator is different than a move constructor because a move assignment operator is called on an existing object, while a move constructor is called on an object created by the operation. Thereafter, the other object's data is no longer valid.

    Overloading move assignment operator

    To overload the move assignment operator, the signature of the function must be:

    T& operator=T&& data

    To successfully overload the move assignment operator, the following conditions must be met:

    Consider the following move assignment operator for a simple string class:

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