Skills101

AdvancedC++ Programming · Lesson 12 of 17 · Updated ·

Move Semantics in C++ — rvalue References, std::move, Move Constructor and the Rule of Five

In the copy constructor lesson, a class that owns an array made a deep copy: new memory, then every value copied. That is correct, but often wasteful. If the source object is about to be thrown away anyway, why copy its data? We could simply take its array. That is what move semantics (added in C++11) does. It is one of the main reasons modern C++ code is fast, and a common interview topic.

1. lvalues and rvalues

Every expression in C++ is either an lvalue or an rvalue. A simple way to tell them apart:

  • An lvalue has a name and a lasting address. You can take its address with &. Example: a variable s.
  • An rvalue is a temporary value with no name, which disappears at the end of the statement. Examples: 42, a + b, string("Ravi"), the value returned by a function.
ExpressionKindWhy
s (a variable)lvaluehas a name, lives on
string("Ravi")rvaluetemporary object
s + "!"rvalueresult of an operation, no name
make_name() returning stringrvaluereturned temporary
std::move(s)rvalues cast to "you may move from me"

The key insight: an rvalue is about to die, so nobody will notice if we steal its insides.

2. rvalue references: T&&

C++11 added a new kind of reference, the rvalue reference, written T&&. It binds only to rvalues. This lets us write two versions of a function: one for lvalues (must copy) and one for rvalues (may steal).

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

void take(const string &s) { cout << "lvalue: copy " << s << "\n"; }
void take(string &&s)      { cout << "rvalue: can steal " << s << "\n"; }

int main() {
    string name = "Asha";
    take(name);               // a named variable
    take(string("Ravi"));     // a temporary
    take(name + "!");         // result of +, a temporary
    take(move(name));         // we promise not to need name's value
    return 0;
}
lvalue: copy Asha
rvalue: can steal Ravi
rvalue: can steal Asha!
rvalue: can steal Asha

std::move (in <utility>) does not move anything by itself. It is only a cast that turns an lvalue into an rvalue, so the && overload is chosen. The actual stealing happens inside the function that receives it.

3. The move constructor

A move constructor has the signature T(T &&other). Instead of allocating new memory, it takes the other object's pointer and leaves the other object empty but valid (here: a null pointer and size 0), so its destructor does no harm.

Before the move, a.data points to the heap array. After Buffer c = std::move(a), c.data points to the same array and a.data is nullptr, so no values were copied

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

class Buffer {
    int *data;
    size_t n;
public:
    Buffer(size_t n) : data(new int[n]{}), n(n) { cout << "alloc " << n << "\n"; }
    Buffer(const Buffer &o) : data(new int[o.n]), n(o.n) {          // deep copy
        for (size_t i = 0; i < n; i++) data[i] = o.data[i];
        cout << "copy " << n << "\n";
    }
    Buffer(Buffer &&o) noexcept : data(o.data), n(o.n) {            // move: steal
        o.data = nullptr;                                         // leave o empty
        o.n = 0;
        cout << "move " << n << "\n";
    }
    ~Buffer() { delete[] data; }                                  // delete[] nullptr is safe
    size_t size() const { return n; }
};

int main() {
    Buffer a(5);
    Buffer b = a;               // a is an lvalue: copy
    Buffer c = move(a);         // rvalue: move
    cout << a.size() << " " << b.size() << " " << c.size() << "\n";
    return 0;
}
alloc 5
copy 5
move 5
0 5 5

The copy allocated a second array of 5 ints. The move allocated nothing — it copied one pointer and one number. For a buffer of a million ints, the copy does a million times more work; the move costs the same as for 5 ints.

After a move, a is in a valid but unspecified state. You may destroy it or assign a new value to it, but do not read its old contents.

4. Move assignment and the rule of five

Move assignment is T &operator=(T &&other). Like copy assignment, it replaces the contents of an object that already exists, so it must first free the old data, and it should handle a = std::move(a) safely.

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

class Buffer {
    int *data;
    size_t n;
public:
    Buffer(size_t n) : data(new int[n]{}), n(n) { cout << "alloc " << n << "\n"; }
    Buffer(Buffer &&o) noexcept : data(o.data), n(o.n) { o.data = nullptr; o.n = 0; }
    Buffer &operator=(Buffer &&o) noexcept {
        if (this != &o) {            // guard against self-move
            delete[] data;           // free what we own now
            data = o.data;           // take o's array
            n = o.n;
            o.data = nullptr;        // leave o empty
            o.n = 0;
        }
        cout << "move-assign\n";
        return *this;
    }
    ~Buffer() { delete[] data; }
    size_t size() const { return n; }
};

int main() {
    Buffer a(3), b(10);
    b = move(a);                // b frees its 10 ints, takes a's 3
    b = Buffer(4);              // a temporary is an rvalue: moved, not copied
    cout << a.size() << " " << b.size() << "\n";
    return 0;
}
alloc 3
alloc 10
move-assign
alloc 4
move-assign
0 4

This completes the rule of five: a class that manages a resource by hand should think about all five special functions.

#FunctionSignature
1Destructor~T()
2Copy constructorT(const T &)
3Copy assignmentT &operator=(const T &)
4Move constructorT(T &&) noexcept
5Move assignmentT &operator=(T &&) noexcept

As before, the rule of zero is better still: if your members are vector, string and unique_ptr, the compiler-generated versions copy and move correctly and you write none of these.

5. Why noexcept matters: vectors and moves

When a vector grows, it moves its old elements into a bigger block. If an element's move constructor might throw an exception halfway, the vector could be left broken. So vector uses your move constructor only if it is marked noexcept (a promise that it will not throw); otherwise it falls back to copying. Moves only swap pointers, so they can almost always be noexcept — always mark them.

The same Buffer also shows the difference between push_back and emplace_back:

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

class Buffer {
    int *data;
    size_t n;
public:
    Buffer(size_t n) : data(new int[n]{}), n(n) { cout << "alloc " << n << "\n"; }
    Buffer(const Buffer &o) : data(new int[o.n]), n(o.n) { cout << "copy " << n << "\n"; }
    Buffer(Buffer &&o) noexcept : data(o.data), n(o.n) {
        o.data = nullptr; o.n = 0;
        cout << "move " << n << "\n";
    }
    ~Buffer() { delete[] data; }
};

int main() {
    vector<Buffer> v;
    v.reserve(4);              // room for 4, so no regrowth in this demo
    v.push_back(Buffer(3));    // build a temporary, then move it in
    v.emplace_back(4);         // build directly inside the vector
    Buffer a(5);
    v.push_back(a);            // a is an lvalue: copied
    v.push_back(move(a));      // moved
    return 0;
}
alloc 3
move 3
alloc 4
alloc 5
copy 5
move 5

emplace_back(4) passes the argument 4 to the constructor and builds the object in place, so there is neither a copy nor a move.

6. Returning objects: copy elision

Returning a big object by value is cheap in modern C++. When a function returns a temporary, as in return Buffer(8);, C++17 guarantees the object is built directly in the caller's variable — no copy and no move. This is called copy elision.

#include <iostream>
using namespace std;

class Buffer {
    size_t n;
public:
    Buffer(size_t n) : n(n) { cout << "alloc " << n << "\n"; }
    Buffer(const Buffer &o) : n(o.n) { cout << "copy\n"; }
    Buffer(Buffer &&o) noexcept : n(o.n) { cout << "move\n"; }
    size_t size() const { return n; }
};

Buffer make(size_t n) {
    return Buffer(n);          // built straight into the caller's object
}

int main() {
    Buffer x = make(8);
    cout << x.size() << "\n";
    return 0;
}
alloc 8
8

When you return a named local (Buffer t(8); return t;), compilers usually elide the copy too (named return value optimisation). If they cannot, the language moves t automatically. So never write return std::move(t); — it can stop the optimisation and gains nothing.

Table of which constructor runs: copying from a named object calls the copy constructor, while std::move, temporaries and returned values use the move constructor or no constructor at all

Common mistakes

  • Thinking std::move moves data. It is only a cast; the move constructor or move assignment does the work.
  • Using an object after moving from it and expecting its old value. It is valid but unspecified.
  • Forgetting to reset the source pointer to nullptr in a move constructor — both destructors then delete the same array.
  • Leaving out noexcept on move operations, so vector silently copies instead of moving.
  • Writing return std::move(local); — it blocks copy elision.
  • Calling std::move on a const object: the const T&& cannot bind to T&&, so the copy constructor runs instead.

Quick recap

  • lvalue: has a name and lasts. rvalue: a temporary about to disappear.
  • T&& is an rvalue reference; it lets a function know its argument may be stolen from.
  • std::move(x) casts x to an rvalue; it moves nothing by itself.
  • Move constructor and move assignment take the pointer and leave the source empty but valid.
  • Mark moves noexcept so containers use them.
  • Rule of five: destructor, copy constructor, copy assignment, move constructor, move assignment. Rule of zero: let vector, string and smart pointers handle it.
  • Returning by value is cheap: copy elision, or an automatic move.

Practice what you learned

📝 Quiz: Move Semantics and rvalue References5 questions · instant answers & explanations · +10 XP · counts towards your free certificateTake the quiz →