SyntaxPilot
Courses/C++/Lesson 29
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

C++ · Lesson 29 of 40

Move semantics

queued

These are the notes for C++ episode 29. In episode 28 a unique_ptr couldn't be copied, so we handed it over with move(). This episode shows what move really does, why C++ copies big objects you were about to throw away, and how a move constructor fixes it. Every example below was compiled with g++ -O2 -std=c++17 main.cpp -o main (g++ 13.3, the same command as the SyntaxPilot compiler) and run; outputs and error messages are copied from those runs.

All the examples use a Playlist that keeps its songs in an array on the heap (episode 10), like a real music app holding a million songs. Its copy constructor (episode 13) makes a deep copy and prints COPY, so you can see every copy happen.

The problem: storing a playlist copies a million songs

A freshly made playlist is pushed into the library. That playlist is a temporary: it's destroyed right after push_back. Yet C++ copies all of it:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

struct Playlist {
    string name; int n; int* songs;
    Playlist(string s, int c) : name(s), n(c), songs(new int[c]) {
        cout << "make " << name << endl;
    }
    Playlist(const Playlist& o) : name(o.name), n(o.n) {
        songs = new int[n];
        for (int i = 0; i < n; i++) songs[i] = o.songs[i];
        cout << "COPY " << n << " songs of " << name << endl;
    }
    ~Playlist() { delete[] songs; }
};

int main() {
    vector<Playlist> library;
    library.reserve(2);                // room for 2
    library.push_back(Playlist("Bollywood", 1000000));
    library.push_back(Playlist("Lo-fi", 1000000));
    cout << "library ready" << endl;
    return 0;
}

Output:

make Bollywood
COPY 1000000 songs of Bollywood
make Lo-fi
COPY 1000000 songs of Lo-fi
library ready

Two million songs copied, and both originals thrown away a moment later. Before C++11 the language only knew one way to pass an object along: copy it. It had no way to say "this object is about to die, just take its stuff".

Step 1: the idea, moving house

Moving house In C++
Building a copy of every chair in the new flat, then burning the old ones Copy: a new array, every song copied
Loading the same furniture into a truck Move: take the pointer to the array; nothing is duplicated
The old flat is still a flat, just empty The moved-from object still exists, valid but empty
You only empty a flat you are leaving Only move from objects nobody needs any more

Step 2: lvalues and rvalues

To move safely, C++ has to know whether an object is still needed.

Kind Plain meaning Examples Safe to empty?
lvalue has a name; you can use it again on the next line city, library, p no
rvalue a temporary with no name; nobody can use it again Playlist("Lo-fi", 5), city + " station", 42 yes

C++11 added the rvalue reference, written with two ampersands: string&&. It binds only to rvalues, so a function that takes one knows it may empty its argument. Overloading on const string& and string&& shows which kind each argument is:

#include <iostream>
#include <string>
using namespace std;

void take(const string& s) {
    cout << "lvalue (named): " << s << endl;
}
void take(string&& s) {
    cout << "rvalue (temporary): " << s << endl;
}

int main() {
    string city = "Pune";
    take(city);                    // has a name
    take(city + " station");      // a temporary
    take(move(city));              // "treat it as a temporary"
    cout << "city is still: " << city << endl;
    return 0;
}

Output:

lvalue (named): Pune
rvalue (temporary): Pune station
rvalue (temporary): Pune
city is still: Pune

The last line matters: city is still Pune. std::move moves nothing. It is only a cast that says "treat this as an rvalue, I won't need it". The function that receives it decides whether to take its contents (here, take(string&&) only printed it).

Step 3: the move constructor

A move constructor takes a Playlist&& and steals the contents instead of copying them:

  1. take the pointer (songs = o.songs;), no new array, no loop;
  2. leave the old object empty (o.songs = nullptr; o.n = 0;), or its destructor would delete the songs we just took (a double delete);
  3. the old object's destructor now deletes nothing (delete[] nullptr does nothing).
Playlist(Playlist&& o) noexcept : name(move(o.name)), n(o.n) {
    songs = o.songs;              // take the pointer
    o.songs = nullptr; o.n = 0;   // leave o empty
    cout << "MOVE " << name << " (no copy)" << endl;
}

The same main as before, now with a move constructor:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

struct Playlist {
    string name; int n; int* songs;
    Playlist(string s, int c) : name(s), n(c), songs(new int[c]) {
        cout << "make " << name << endl;
    }
    Playlist(const Playlist& o) : name(o.name), n(o.n) {
        songs = new int[n];
        for (int i = 0; i < n; i++) songs[i] = o.songs[i];
        cout << "COPY " << n << " songs of " << name << endl;
    }
    Playlist(Playlist&& o) noexcept : name(move(o.name)), n(o.n) {
        songs = o.songs;              // take the pointer
        o.songs = nullptr; o.n = 0;   // leave o empty
        cout << "MOVE " << name << " (no copy)" << endl;
    }
    ~Playlist() { delete[] songs; }
};

int main() {
    vector<Playlist> library;
    library.reserve(2);                // room for 2
    library.push_back(Playlist("Bollywood", 1000000));
    library.push_back(Playlist("Lo-fi", 1000000));
    cout << "library ready" << endl;
    return 0;
}

Output:

make Bollywood
MOVE Bollywood (no copy)
make Lo-fi
MOVE Lo-fi (no copy)
library ready

main didn't change. The playlist inside push_back is an rvalue, so C++ picked the move constructor by itself. That is move semantics: the compiler sees an object is leaving and steals instead of copying.

How much does it save?

vector<int> already has a move constructor. Copying 10 million ints is 10 million steps; moving is three pointers:

#include <iostream>
#include <vector>
#include <chrono>
using namespace std;

using Time = chrono::steady_clock::time_point;
long long micros(Time a, Time b) {           // microseconds from a to b
    return chrono::duration_cast<chrono::microseconds>(b - a).count();
}

int main() {
    vector<int> songs(10000000, 7);          // 10 million songs
    auto t0 = chrono::steady_clock::now();
    vector<int> backup = songs;              // copy
    auto t1 = chrono::steady_clock::now();
    vector<int> moved = move(songs);         // move
    auto t2 = chrono::steady_clock::now();
    cout << "copy: " << micros(t0, t1) << " microseconds" << endl;
    cout << "move: " << micros(t1, t2) << " microseconds" << endl;
    cout << "songs now has " << songs.size() << " songs" << endl;
    return 0;
}

Output:

copy: 21531 microseconds
move: 0 microseconds
songs now has 0 songs

The copy time depends on the machine (tens of thousands of microseconds here); the move is always about zero. After the move, songs is empty: moved owns its array. Don't use a moved-from object again until you give it a new value (songs = {1, 2, 3}; or songs.clear(); is fine).

Step 4: noexcept, or the vector copies anyway

When a vector is full, push_back allocates a bigger block and must bring every old element across. The vector promises that if anything fails, it is left as it was (the strong exception guarantee). If a move threw halfway, some elements would already be emptied, so the vector only moves when the move constructor is marked noexcept ("this never throws"). Without it:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

struct Playlist {
    string name; int n; int* songs;
    Playlist(string s, int c) : name(s), n(c), songs(new int[c]) {
        cout << "make " << name << endl;
    }
    Playlist(const Playlist& o) : name(o.name), n(o.n) {
        songs = new int[n];
        for (int i = 0; i < n; i++) songs[i] = o.songs[i];
        cout << "COPY " << n << " songs of " << name << endl;
    }
    Playlist(Playlist&& o) : name(move(o.name)), n(o.n) {
        songs = o.songs;              // take the pointer
        o.songs = nullptr; o.n = 0;   // leave o empty
        cout << "MOVE " << name << " (no copy)" << endl;
    }
    ~Playlist() { delete[] songs; }
};

int main() {
    vector<Playlist> library;           // no reserve this time
    library.push_back(Playlist("Bollywood", 1000000));
    library.push_back(Playlist("Lo-fi", 1000000));
    library.push_back(Playlist("Retro", 1000000));
    cout << "library ready" << endl;
    return 0;
}

Output:

make Bollywood
MOVE Bollywood (no copy)
make Lo-fi
MOVE Lo-fi (no copy)
COPY 1000000 songs of Bollywood
make Retro
MOVE Retro (no copy)
COPY 1000000 songs of Bollywood
COPY 1000000 songs of Lo-fi
library ready

Each time the vector grew, it copied the old playlists: three million songs. With noexcept:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

struct Playlist {
    string name; int n; int* songs;
    Playlist(string s, int c) : name(s), n(c), songs(new int[c]) {
        cout << "make " << name << endl;
    }
    Playlist(const Playlist& o) : name(o.name), n(o.n) {
        songs = new int[n];
        for (int i = 0; i < n; i++) songs[i] = o.songs[i];
        cout << "COPY " << n << " songs of " << name << endl;
    }
    Playlist(Playlist&& o) noexcept : name(move(o.name)), n(o.n) {
        songs = o.songs;              // take the pointer
        o.songs = nullptr; o.n = 0;   // leave o empty
        cout << "MOVE " << name << " (no copy)" << endl;
    }
    ~Playlist() { delete[] songs; }
};

int main() {
    vector<Playlist> library;           // no reserve this time
    library.push_back(Playlist("Bollywood", 1000000));
    library.push_back(Playlist("Lo-fi", 1000000));
    library.push_back(Playlist("Retro", 1000000));
    cout << "library ready" << endl;
    return 0;
}

Output:

make Bollywood
MOVE Bollywood (no copy)
make Lo-fi
MOVE Lo-fi (no copy)
MOVE Bollywood (no copy)
make Retro
MOVE Retro (no copy)
MOVE Bollywood (no copy)
MOVE Lo-fi (no copy)
library ready

Every element is moved, also when the vector grows. Taking a pointer and writing nullptr can't fail, so the promise is true. Always mark move constructors (and move assignment) noexcept.

Two traps

Moving a const silently copies

#include <iostream>
#include <string>
using namespace std;

struct Playlist {
    string name; int n; int* songs;
    Playlist(string s, int c) : name(s), n(c), songs(new int[c]) {
        cout << "make " << name << endl;
    }
    Playlist(const Playlist& o) : name(o.name), n(o.n) {
        songs = new int[n];
        for (int i = 0; i < n; i++) songs[i] = o.songs[i];
        cout << "COPY " << n << " songs of " << name << endl;
    }
    Playlist(Playlist&& o) noexcept : name(move(o.name)), n(o.n) {
        songs = o.songs;              // take the pointer
        o.songs = nullptr; o.n = 0;   // leave o empty
        cout << "MOVE " << name << " (no copy)" << endl;
    }
    ~Playlist() { delete[] songs; }
};

int main() {
    const Playlist fav("Favourites", 1000000);
    Playlist trip = move(fav);        // move... a const?
    cout << "fav still has " << fav.n << " songs" << endl;
    return 0;
}

Output:

make Favourites
COPY 1000000 songs of Favourites
fav still has 1000000 songs

Moving empties the source, and a const object can't be changed. move(fav) gives a const Playlist&&, which can't bind to Playlist&&, so C++ quietly falls back to the copy constructor. No error, no warning. If you plan to move something, don't make it const.

Don't write return move(local)

#include <iostream>
#include <string>
using namespace std;

struct Playlist {
    string name; int n; int* songs;
    Playlist(string s, int c) : name(s), n(c), songs(new int[c]) {
        cout << "make " << name << endl;
    }
    Playlist(const Playlist& o) : name(o.name), n(o.n), songs(new int[o.n]) {
        for (int i = 0; i < n; i++) songs[i] = o.songs[i];
        cout << "COPY" << endl;
    }
    Playlist(Playlist&& o) noexcept : name(move(o.name)), n(o.n), songs(o.songs) {
        o.songs = nullptr; o.n = 0;
        cout << "MOVE " << name << " (no copy)" << endl;
    }
    ~Playlist() { delete[] songs; }
};

Playlist plain() {
    Playlist p("Road trip", 1000000);
    return p;                    // copy elision: no copy, no move
}
Playlist withMove() {
    Playlist p("Road trip", 1000000);
    return move(p);              // forces a move
}

int main() {
    Playlist a = plain();
    cout << "got " << a.name << endl;
    Playlist b = withMove();
    cout << "got " << b.name << endl;
    return 0;
}

Output:

make Road trip
got Road trip
make Road trip
MOVE Road trip (no copy)
got Road trip

return p; builds p directly in the caller's variable (copy elision, often called RVO/NRVO), so there is no copy and no move at all. return move(p); blocks that and forces an extra move. With warnings switched on (g++ -Wall), g++ says: warning: moving a local object in a return statement prevents copy elision [-Wpessimizing-move]. Return local variables plainly.

The rule of five (and the better rule of zero)

A class that manages a resource by hand (a raw pointer, a file handle) needs all five special member functions:

Function Written as Runs on
destructor ~Playlist() destruction
copy constructor Playlist(const Playlist& o) Playlist b = a;
copy assignment Playlist& operator=(const Playlist& o) b = a;
move constructor Playlist(Playlist&& o) noexcept Playlist b = move(a);, temporaries
move assignment Playlist& operator=(Playlist&& o) noexcept b = move(a);

If you write one of them, think about all five: that's the rule of five. Better still is the rule of zero: keep the songs in a vector<int> (or a unique_ptr<int[]>) and write none of them; the compiler generates correct copies and moves for you.

Common mistakes (and the real g++ messages)

Mistake What happens Fix
Move constructor that doesn't empty the source: songs = o.songs; only compiles; both destructors delete[] the same array: undefined behaviour (a double delete) o.songs = nullptr;
Move constructor without noexcept compiles; every time a vector grows it copies the elements Playlist(Playlist&& o) noexcept
move() on a const object compiles; silently copies don't make it const if you'll move it
return move(p); for a local p warning: moving a local object in a return statement prevents copy elision [-Wpessimizing-move] (with -Wall) return p;
Reading an object after moving from it compiles; valid but unspecified contents (usually empty) assign a new value first
Thinking std::move moves nothing happens until a move constructor/assignment receives it move is only a cast

Mini project: a playlist with move assignment

The homework asks for move assignment. Here is a complete, rule-of-five Playlist, and a swap that never copies a song:

#include <iostream>
#include <string>
using namespace std;

struct Playlist {
    string name; int n = 0; int* songs = nullptr;
    Playlist(string s, int c) : name(s), n(c), songs(new int[c]) {}
    Playlist(const Playlist& o) : name(o.name), n(o.n), songs(new int[o.n]) {
        for (int i = 0; i < n; i++) songs[i] = o.songs[i];
        cout << "COPY " << name << endl;
    }
    Playlist(Playlist&& o) noexcept : name(move(o.name)), n(o.n), songs(o.songs) {
        o.songs = nullptr; o.n = 0;
        cout << "MOVE-CONSTRUCT " << name << endl;
    }
    Playlist& operator=(const Playlist& o) {
        if (this == &o) return *this;          // a = a
        Playlist tmp(o);                       // copy first, then swap in
        swap(name, tmp.name); swap(n, tmp.n); swap(songs, tmp.songs);
        return *this;
    }
    Playlist& operator=(Playlist&& o) noexcept {
        if (this == &o) return *this;
        delete[] songs;                        // give back what we had
        name = move(o.name); n = o.n; songs = o.songs;
        o.songs = nullptr; o.n = 0;            // leave o empty
        cout << "MOVE-ASSIGN " << name << endl;
        return *this;
    }
    ~Playlist() { delete[] songs; }
};

void swapPlaylists(Playlist& a, Playlist& b) {
    Playlist tmp = move(a);
    a = move(b);
    b = move(tmp);
}

int main() {
    Playlist morning("Morning", 1000000), night("Night", 500000);
    swapPlaylists(morning, night);
    cout << morning.name << " has " << morning.n << " songs" << endl;
    cout << night.name << " has " << night.n << " songs" << endl;
    return 0;
}

Output:

MOVE-CONSTRUCT Morning
MOVE-ASSIGN Night
MOVE-ASSIGN Morning
Night has 500000 songs
Morning has 1000000 songs

Three moves, zero songs copied. (This is exactly what std::swap does for types that can be moved.)

Practice

  1. Add a move constructor to a class that owns a raw array, and print COPY/MOVE to prove which one runs.
  2. Push 3 objects into a vector without reserve, with and without noexcept on the move constructor, and compare the output.
  3. Time copying vs moving a vector<string> of 1 million strings.
  4. Write move assignment operator=(Playlist&&) (the mini project above is one answer).
Solutions

Exercise 1 and 2 are the noexcept programs above: without noexcept the vector prints COPY when it grows, with it every line is MOVE.

Exercise 3:

#include <iostream>
#include <string>
#include <vector>
#include <chrono>
using namespace std;
using Clock = chrono::steady_clock;

long long ms(Clock::time_point a, Clock::time_point b) {
    return chrono::duration_cast<chrono::milliseconds>(b - a).count();
}

int main() {
    vector<string> names(1000000, "a song title long enough to live on the heap");
    auto t0 = Clock::now();
    vector<string> copy = names;
    auto t1 = Clock::now();
    vector<string> moved = move(names);
    auto t2 = Clock::now();
    cout << "copy took more than 1 ms: " << (ms(t0, t1) >= 1 ? "yes" : "no") << endl;
    cout << "move took 0 ms: " << (ms(t1, t2) == 0 ? "yes" : "no") << endl;
    cout << "copy has " << copy.size() << ", moved has " << moved.size() << ", names has " << names.size() << endl;
    return 0;
}

Output:

copy took more than 1 ms: yes
move took 0 ms: yes
copy has 1000000, moved has 1000000, names has 0

Copying a million strings copies a million heap buffers; moving the vector copies three pointers.

Quick quiz

Which line copies the string?

vector<string> v;
string s = "chai";
v.push_back(s);           // A
v.push_back(s + "!");     // B
v.push_back(move(s));     // C
Answer

A only. s is a named lvalue, so push_back(const string&) copies it. s + "!" is a temporary (rvalue), so push_back(string&&) moves it. move(s) casts s to an rvalue, so it is moved too (and s is left valid but unspecified).

Interview questions

  1. What is an rvalue reference? A reference declared with && that binds only to rvalues (temporaries or things cast with std::move), so the receiver may steal their contents.
  2. What does std::move do? Nothing at run time: it is a cast to an rvalue reference (static_cast<T&&>). The move happens only if a move constructor or move assignment receives it.
  3. Why should a move constructor be noexcept? std::vector (and other containers) use std::move_if_noexcept when they reallocate; if the move might throw they copy instead, to keep the strong exception guarantee.
  4. What state is a moved-from object in? Valid but unspecified: you may destroy it or assign to it; don't rely on its value.
  5. What is copy elision / RVO? The compiler constructs a returned object directly in the caller's storage, so no copy or move runs. Since C++17 it is guaranteed for returning a temporary (return Playlist(...)).
  6. Why is return std::move(local); bad? It prevents copy elision and forces a move (-Wpessimizing-move).
  7. What is the rule of five? The rule of zero? A class that defines any of destructor/copy/move operations should consider all five; better, use members (vector, string, unique_ptr) that manage themselves and define none.
  8. When does the compiler generate a move constructor for you? When you declare no copy operations, no move operations and no destructor yourself.

Glossary

Term Meaning, with an example
copy Making a second, independent object with the same contents; for a Playlist, a new array with every song copied.
deep copy A copy that duplicates the heap data too, not just the pointer (episode 13).
move Handing an object's contents (e.g. its array pointer) to another object instead of copying them.
move semantics The C++11 rules that let the compiler move from objects that are about to die.
temporary An unnamed object that dies at the end of the statement: Playlist("Lo-fi", 5) inside push_back.
lvalue An expression with a name/identity you can use again: city, library[0].
rvalue A temporary or a value that is about to expire: city + " station", 42, move(city).
rvalue reference (&&) string&& s: a reference that binds only to rvalues.
std::move A cast to an rvalue reference: "treat this as a temporary". It moves nothing by itself.
move constructor Playlist(Playlist&& o): builds a new object by stealing o's contents.
move assignment Playlist& operator=(Playlist&& o): replaces an existing object's contents with o's.
moved-from object The source after a move: valid but unspecified (usually empty).
nullptr The null pointer; delete[] nullptr does nothing.
noexcept A promise that a function never throws an exception; containers rely on it to move.
reallocation A full vector getting a bigger block and bringing its elements across.
strong exception guarantee "If this fails, nothing changed": why vector copies when a move might throw.
copy elision / RVO The compiler builds a returned object straight in the caller's variable: no copy, no move.
rule of five Destructor, copy constructor, copy assignment, move constructor, move assignment: write one, think about all five.
rule of zero Let members like vector and unique_ptr manage resources, and write none of the five.
std::chrono The time library: steady_clock::now() reads a clock for timing code.

Summary

  • Storing a temporary used to copy it, even though it was about to die.
  • lvalues have names; rvalues are temporaries. T&& binds only to rvalues.
  • std::move only casts; a move constructor does the work: take the pointer, leave the source empty.
  • Mark moves noexcept, or vector copies when it grows.
  • Moving a const copies; return locals plainly (return p;).
  • Rule of five, or better, the rule of zero.

Next episode: sorting students by marks needs a whole separate function just to compare two of them. What if you could write that function right inside the sort call? Lambdas.