C++ Move Semantics Move assignment

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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.



Got any C++ Question?