CodeBlanks Logo Icon CodeBlanks

Move assignment

Learn the move assignment operator.

Move assignment

Move assignment runs when an rvalue is assigned to an existing object. Its signature is T& operator=(T&& other).

Example: Bag& operator=(Bag&& other) { item = std::move(other.item); return *this; }. Here the assignment b = std::move(a); triggers move assignment. other.item is moved with std::move and *this is returned. The move constructor creates a new object while move assignment changes the content of an existing one. Both are part of move semantics.

operator= and *this

The move assignment operator returns *this; this enables chained assignment (a = b = c). Resource cleanup must also be done.

Example: Bag& operator=(Bag&& other) { item = std::move(other.item); return *this; }. The line item = std::move(other.item) releases the old content and moves the new one. return *this returns a reference to itself. If the class holds a raw pointer, the old resource must be deleted before move assignment. Classes like std::string handle this automatically, so no extra cleanup is needed.

Practice Add move assignment to the Bag class

Add move assignment to the Bag class in the starting code: Bag& operator=(Bag&& other) { item = std::move(other.item); return *this; }. In main move a into b with b = std::move(a); and print b.item with std::cout.

Starter code

main.cpp
#include <iostream>
#include <string>
#include <utility>

class Bag {
public:
    std::string item;
    Bag(std::string i) : item(i) {}
    // Add move assignment
};

int main() {
    Bag a("Apple");
    Bag b("Banana");
    // Move a into b and print b.item
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <string>
#include <utility>

class Bag {
public:
    std::string item;
    Bag(std::string i) : item(i) {}
    Bag& operator=(Bag&& other) {
        item = std::move(other.item);
        return *this;
    }
};

int main() {
    Bag a("Apple");
    Bag b("Banana");
    b = std::move(a);
    std::cout << b.item;
    return 0;
}

Expected output

Apple

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does b = std::move(a); trigger?

main.cpp
Bag a("Apple"), b("Banana");
b = std::move(a);
  • Copy constructor
  • Move assignment Correct answer
  • Copy assignment
  • Move constructor

Explanation: Assigning to an existing object triggers move assignment.

2 Match each operation to its trigger

Term Meaning
Box b(std::move(a)) Move constructor
b = std::move(a) Move assignment
Box b(a) Copy constructor
b = a Copy assignment

3 Move assignment signature

Question
Bag& operator=(Bag____ other) { item = std::move(other.item); return *this; }
Answer
Bag& operator=(Bag&& other) { item = std::move(other.item); return *this; }

Explanation: Move assignment takes an rvalue reference: Bag&&.

All lessons in Intermediate