Move assignment operator

This is an old revision of this page, as edited by Gregm1016 (talk | contribs) at 00:57, 23 February 2016 (Created page with 'In the C++ programming language, the move assignment operator (=), is used for moving an already instantiated object or resource to another ___location. The...'). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

In the C++ programming language, the move assignment operator (=), is used for moving an already instantiated object or resource to another ___location. The move operator, like most of the other C++ operators, can be overloaded. It is one the of the special member functions.[1]

If the move assignment operator is not explicitly defined, then the compiler will generate an implicit move assignment operator. The parameters of a move assignment operator are an rvalue reference (T&&) to type T, where T is the type the move assignment operator is called on, or any overloaded type. The move assignment operator is different than a move constructor because a move assignment operator is called on an existing object, as a move constructor would be called on an object being created. One must somehow also signify the other object's data is not valid anymore, and has been moved.

__FORCETOC__

Overloading move assignment operator

To overload the move assignment operator, the signature of the function must be as follows:[2]

T& operator=(T&& data)

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

  • Check if the object calling the operator is not calling the operator on itself.
  • The current object's data is de-allocated.
  • The object that is being moved from must have its data marked as nullptr (or something to signify the move)
  • The operator returns a reference to "*this".

An implementation of the move assignment operator:

class Resource {

public:

    Resource& operator=(Resource&& other) {
    
        if (this != &other) {           // If the object isn't being called on itself
            delete this->data;          // Delete the object's data
            this->data = other.data;    // "Move" other's data into the current object
            other.data = nullptr;       // Mark the other object as "empty"
        }
        return *this;                   // return *this
    }

    void* data;

};

A more practical example:

class String {

public:

    String& operator=(String&& otherString) {
    
        if (this != &otherString) {
            delete text;
            this->text = otherString.text;
            otherString.text = nulllptr;
        }
        return *this;
    }

    char* text;

};
  1. ^ "Special member functions". Wikipedia, the free encyclopedia.
  2. ^ "Move assignment operator - cppreference.com". en.cppreference.com. Retrieved 2016-02-23.