Contributors: 3 Wednesday, May 3, 2017
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial:
Roadmap: roadmap

Move assignment

Download c++ eBook


Similarly to how we can assign a value to an object with an lvalue reference, copying it, we can also move the values from an object to another without constructing a new one. We call this move assignment. We move the values from one object to another existing object.

For this, we will have to overload operator =, not so that it takes an lvalue reference, like in copy assignment, but so that it takes an rvalue reference.

class A {
    int a;
    A& operator= (A&& other) {
        this->a = other.a;
        other.a = 0;
        return *this;

This is the typical syntax to define move assignment. We overload operator = so that we can feed it an rvalue reference and it can assign it to another object.

A a;
a.a = 1;
A b;
b = std::move(a); //calling A& operator= (A&& other)
std::cout << a.a << std::endl; //0
std::cout << b.a << std::endl; //1

Thus, we can move assign an object to another one.