The move assignment operator lets an existing object take ownership of another object's external resources instead of copying them. By transferring ownership of the resource (e.g. heap memory, file handles, sockets), the underlying data is not reallocated thus cheaper to move. Built-in fields are instead copied.

The move assignment is declared as operator= and takes an rvalue reference (&&) argument:

class Buffer {
public:
  Buffer(int n) : size(n), data(new int[n]) {}
  Buffer& operator=(Buffer&& other) noexcept {
    if (this != &other) {
      delete[] data;
      size = other.size;
      data = other.data;

      // Invalidate moved-from object's fields to prevent accidental free and side-effects.
      other.size = 0;
      other.data = nullptr;
    }
    return *this;
  }
  ~Buffer() { delete[] data; }
  int size;
  int* data;
};

Warning

Check this != &other, otherwise self-assignment deletes data before moving it.

Note

Mark the move assignment noexcept. Code that guarantees no change on failure checks for noexcept to decide whether it can move safely.

Note

The copy-and-swap idiom can be used to implement the move assignment.

The move assignment is invoked when the object already exists, and the right-hand side is an rvalue (temporary or cast with std::move#include <utility>()):

Buffer a(10);
Buffer b(20);
b = std::move#include <utility>(a);  // b frees its array and takes a's.
b.size;            // 10
a.data;            // nullptr

b = Buffer(30);    // b frees a's old array and takes the temporary's.
b.size;            // 30

The move assignment operator can be deleted to prevent usage:

class Buffer {
public:
  Buffer& operator=(Buffer&&) = delete;
};

b = std::move#include <utility>(a);  // ERROR.

The move assignment operator can be defaulted to let the compiler generate it:

class Buffer {
public:
  Buffer& operator=(Buffer&&) = default;
};

Warning

The compiler-generated move assignment moves each field but does not invalidate the moved-from object's fields.

References