Thuta Learning
C++
AdvancedProgrammingBeginner

Move Semantics & Rule of Zero

C++Lesson 1735 min

What you'll walk away with

  • Explain the difference between copying and moving a std::string or std::vector
  • Use std::move to hand an object you no longer need to a new owner, and say what std::move itself does
  • Use a moved-from object correctly: assign or destroy it, never rely on its old value
  • Apply the rule of zero, and recognise when the rule of five applies

Explain it simply

Explain it simply

Copying a suitcase means buying a second suitcase and packing identical clothes into it. Moving it means handing the suitcase you already have to someone else. Both leave the other person with a full suitcase, but moving costs almost nothing, and afterwards your hands are empty.

C++ objects like std::string and std::vector work the same way. Their data lives in a buffer on the heap, so a copy must allocate a new buffer and copy every element, while a move simply hands over the pointer to the existing buffer. You ask for a move with std::move when you no longer need the original.

Problem → Why → Solution

The problem: copies that cost too much, and copies that crash

Copies have two costs in C++. The obvious one is performance: pushing a one-million-element vector into another container by name copies all one million elements, even when the original is never used again. The less obvious one appears when a class manages memory by hand. The Buffer class below owns an array through a raw pointer. The compiler-generated copy copies the pointer, not the array, so two Buffers end up owning the same memory, and both destructors delete it.

buffer.cpp
class Buffer {
public:
    explicit Buffer(int size) : data_(new int[size]) {}
    ~Buffer() { delete[] data_; }

private:
    int* data_;
};

int main() {
    Buffer a(100);
    Buffer b = a;   // copies the pointer, not the 100 ints
}                   // b deletes the array, then a deletes it again

Why the default copy goes wrong here

The compiler writes copy and move operations that copy or move each member. For a std::vector member that does the right thing, because the vector knows how to copy itself. For a raw int* it copies the address, so ownership is duplicated and the second delete[] is undefined behaviour. Either you write all the special member functions yourself or, much better, you hold the array in a std::vector and write none of them.

Core concept: lvalues, rvalues and std::move

Every object you can name, such as source or demo, is an lvalue. Initialising a new object from an lvalue calls the copy constructor, because the original is still in use and must not change. A temporary, such as the result of a function call, is an rvalue: nobody can refer to it afterwards, so it is safe to steal its contents. The move constructor, which takes a T&& (an rvalue reference), does exactly that: a std::string or std::vector moves by taking the source's heap pointer and leaving the source with nothing to free.

text
Copy versus move of a Track
---------------------------
 Track copy = demo;              Track moved = std::move(demo);

 demo.samples --> [7,7,7,...]    demo.samples  --x  (pointer handed over)
 copy.samples --> [7,7,7,...]    moved.samples --> [7,7,7,...]
   new buffer: 1,000,000 ints     same buffer: nothing copied
   copied one by one              demo: valid, contents unspecified

std::move does not move anything. It is a cast that turns an lvalue into an rvalue, as if to say "I am finished with this object, you may take its contents". The move itself happens only if the receiving side has a move constructor or move assignment that accepts it. If the object is const, a move cannot modify it, so std::move(constObj) silently falls back to a copy. A bare statement std::move(s); does nothing at all, and GCC warns that its nodiscard result is ignored.

After a move, the source is in a valid but unspecified state. It is still a real object: you may assign it a new value, call functions without preconditions such as clear() or empty(), or let it be destroyed. What you must not do is rely on what it contains. A moved-from std::string is often empty in practice, but the standard does not promise that; std::unique_ptr is one of the few types that does guarantee a moved-from object is null.

The special member functions are the destructor, copy constructor, copy assignment, move constructor and move assignment. The rule of zero says: if every member already manages itself (strings, vectors, smart pointers), declare none of the five, and the compiler-generated ones copy, move and destroy correctly. The rule of five says: if you must write one of them because the class directly manages a resource, think about all five, because the defaults for the others are probably wrong.

ExpressionWhat it calls
T b = a;copy constructor
T b = std::move(a);move constructor (a copy if a is const)
b = a;copy assignment
b = std::move(a);move assignment
Mental model: copy duplicates, move hands over
  1. Named object (lvalue): copy
  2. std::move casts it to an rvalue
  3. Move ctor takes the heap buffer
  4. Source: valid, contents unspecified

std::move is a promise that you are done with the object; the type's move constructor is what acts on it.

General pattern

cpp
Type b = a;              // copy: a is unchanged
Type c = std::move(a);   // move: a is valid, contents unspecified
a = Type{};              // a moved-from object may be assigned again

void sink(Type value);   // by value: the caller copies or moves into it
sink(std::move(c));

struct Holder {          // rule of zero: no destructor, copy or move written
    std::string text;
    std::vector<int> items;
};

Write std::move only on an object you will not read again before giving it a new value. A sink parameter taken by value lets the caller choose: pass a name to copy, or std::move(name) to move. A class whose members are all self-managing types follows the rule of zero.

Example: copying versus moving a big Track

Track has a title and a million audio samples, and it declares no special member functions at all. The program copies one Track, moves it into a second one, then gives the moved-from object a fresh value. Notice that it never prints demo between the move and the reassignment, because its contents at that point are unspecified.

track.cpp
#include <iostream>
#include <string>
#include <utility>
#include <vector>

struct Track {
    std::string title;
    std::vector<int> samples;
};

int main() {
    Track demo{"demo", std::vector<int>(1'000'000, 7)};

    Track copy = demo;
    Track moved = std::move(demo);

    std::cout << "copy:  " << copy.title << ", " << copy.samples.size() << '\n';
    std::cout << "moved: " << moved.title << ", " << moved.samples.size() << '\n';

    demo = Track{"fresh", {1, 2, 3}};
    std::cout << "demo:  " << demo.title << ", " << demo.samples.size() << '\n';
}

Code breakdown

  1. Lines 6-9struct Track {

    Two self-managing members and no destructor, copy or move functions: the rule of zero. The compiler generates all five, and each one simply copies or moves the members.

  2. Line 14Track copy = demo;

    demo is a named object, so this calls the copy constructor: a new buffer of one million ints is allocated and filled.

  3. Line 15Track moved = std::move(demo);

    std::move casts demo to an rvalue, so the move constructor runs. The vector inside moved takes demo's buffer pointer; not a single element is copied.

  4. Lines 17-18moved.samples.size()

    Both new Tracks report 1000000 samples and the title demo. moved holds the original buffer; copy holds an independent duplicate.

  5. Line 20demo = Track{"fresh", {1, 2, 3}};

    A moved-from object is still valid, so assigning a brand-new value is allowed. After this line demo's contents are known again and safe to print.

You should see
copy:  demo, 1000000
moved: demo, 1000000
demo:  fresh, 3

Watching copies and moves happen

To see which constructor runs, give a test type a copy constructor and a move constructor that record how each object was made. The output shows the three cases that matter: a named object is copied, std::move on it gives a move, and std::move on a const object quietly becomes a copy, because the move constructor's Probe&& parameter cannot bind to a const object. Probe breaks the rule of zero on purpose, only to make the calls visible.

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

struct Probe {
    std::string how = "made";
    Probe() = default;
    Probe(const Probe&) : how("copied") {}
    Probe(Probe&&) noexcept : how("moved") {}
};

int main() {
    Probe a;
    Probe b = a;               // a is a named object (lvalue)
    Probe c = std::move(a);    // std::move casts a to an rvalue
    const Probe d{};
    Probe e = std::move(d);    // const rvalue cannot bind to Probe&&

    std::cout << "b was " << b.how << '\n';   // copied
    std::cout << "c was " << c.how << '\n';   // moved
    std::cout << "e was " << e.how << '\n';   // copied
}

Make move constructors noexcept

When a std::vector grows, it uses an element's move constructor only if that constructor cannot throw; otherwise it copies, to keep its strong exception guarantee. Compiler-generated moves are already noexcept when the members allow it; on moves you write yourself, add noexcept explicitly.

When you really need the rule of five

Sometimes a class really does manage a resource directly, for example a wrapper around a C library handle. Then it needs a destructor, and the defaults for copying and moving are wrong. The usual fix is to make the type move-only: delete the copy operations, and write a move constructor and move assignment that take the handle and leave the source empty. This Handle defines its own moved-from state (id 0), so reading a.id() after the move is allowed for this type. Before writing any of this, check whether std::unique_ptr with a custom deleter already does the job; it usually does, and it brings you back to the rule of zero.

handle.cpp
#include <iostream>
#include <utility>

class Handle {
public:
    explicit Handle(int id) : id_(id) { std::cout << "acquire " << id_ << '\n'; }
    ~Handle() {
        if (id_ != 0) std::cout << "release " << id_ << '\n';
    }

    Handle(const Handle&) = delete;              // one owner only: no copies
    Handle& operator=(const Handle&) = delete;

    Handle(Handle&& other) noexcept : id_(std::exchange(other.id_, 0)) {}
    Handle& operator=(Handle&& other) noexcept {
        if (this != &other) {
            if (id_ != 0) std::cout << "release " << id_ << '\n';
            id_ = std::exchange(other.id_, 0);
        }
        return *this;
    }

    int id() const { return id_; }

private:
    int id_;
};

int main() {
    Handle a(7);
    Handle b = std::move(a);   // Handle defines its moved-from state: id 0
    std::cout << "a: " << a.id() << ", b: " << b.id() << '\n';

    Handle c(9);
    c = std::move(b);          // c releases 9, then takes 7
    std::cout << "c: " << c.id() << '\n';
}

In real projects

Where this shows up in real projects

Move semantics is why modern C++ can return big objects by value without worry. A function such as std::vector<Order> loadOrders() hands its result to the caller by moving it, or by eliding the copy entirely, so APIs can be written in the natural style. Containers rely on moves too: when a std::vector of strings grows, it moves each string into the new buffer instead of copying the characters, as long as the move constructor is noexcept.

In everyday code you will see std::move at hand-over points: pushing a finished object into a container (orders.push_back(std::move(order))), storing a constructor parameter in a member (name_(std::move(name))), or passing a std::unique_ptr to a new owner. Most classes in a well-written code base follow the rule of zero, which is why the special member functions you do meet usually live in small, low-level wrapper types.

Common mistakes

Common mistakes

1. Using an object after moving from it

std::string t = std::move(s); std::cout << s; compiles and runs, but what it prints is unspecified, and for your own types the moved-from state might break an invariant. After std::move(x), either assign x a new value or stop using it.

2. Expecting std::move to move a const object

const std::string s = "hi"; auto t = std::move(s); copies, because the move constructor cannot modify a const source. No warning appears. Do not declare objects const if you plan to move from them.

3. Writing std::move on a return value

return std::move(result); for a local result can prevent copy elision and make the code slower. GCC warns under -Wall: moving a local object in a return statement prevents copy elision [-Wpessimizing-move]. Write return result; and let the compiler move or elide automatically.

4. Writing special members the compiler would write better

Adding an empty destructor ~Track() {} to a rule-of-zero class looks harmless, but a user-declared destructor stops the compiler from generating the move operations, so every "move" quietly becomes a copy. Leave them out, or write = default for all of them.

Best practices

Best practices

  • Follow the rule of zero: build classes from members that manage themselves.
  • Use std::move only at the last use of an object, at a hand-over point.
  • Mark the move constructors and move assignments you write yourself noexcept.
  • Return local objects with a plain return name;, never with return std::move(name);.

Mini challenge

Mini challenge: an inbox that moves its messages

Build a small inbox using the rule of zero and sink parameters, and decide at each call whether the caller's string should be copied or moved.

  • struct Inbox holds std::string owner and std::vector<std::string> messages, with no special member functions
  • void send(Inbox& inbox, std::string text) takes text by value and moves it into the vector
  • Send one message by name (the caller keeps it) and one with std::move, then give the moved-from string a new value before printing it
  • Move the inbox into an archive vector, and show that a moved-from std::unique_ptr is null
inbox.cpp
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <vector>

struct Inbox {
    // TODO: owner and messages; write no destructor, copy or move functions
};

void send(Inbox& inbox, std::string text) {
    // TODO: move text into inbox.messages
}

Inbox makeInbox(std::string owner) {
    // TODO: build an Inbox for owner and send it "Welcome!"
}

int main() {
    // TODO: make Aye's inbox; send a note by name and a draft with std::move
    // TODO: reassign the draft, then print both strings
    // TODO: move the inbox into a std::vector<Inbox>, print its message count
    // TODO: move a std::unique_ptr<int> and print whether the source is empty
}

Expected: The output should be: note kept: Meeting at 10 draft reused: New draft Aye has 3 messages token empty: true, taken holds 42

Show hint

Inside send(), text is a local copy (or a moved-in string), so inbox.messages.push_back(std::move(text)) costs no extra copy. Print draft only after giving it a new value, because its moved-from contents are unspecified. A std::unique_ptr, by contrast, is guaranteed to be null after a move.

Show solution
inbox.cpp
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <vector>

struct Inbox {
    std::string owner;
    std::vector<std::string> messages;
};

void send(Inbox& inbox, std::string text) {
    inbox.messages.push_back(std::move(text));
}

Inbox makeInbox(std::string owner) {
    Inbox inbox{std::move(owner), {}};
    send(inbox, "Welcome!");
    return inbox;
}

int main() {
    Inbox aye = makeInbox("Aye");

    std::string note = "Meeting at 10";
    send(aye, note);
    std::cout << "note kept: " << note << '\n';

    std::string draft = "Long report text";
    send(aye, std::move(draft));
    draft = "New draft";
    std::cout << "draft reused: " << draft << '\n';

    std::vector<Inbox> archive;
    archive.push_back(std::move(aye));
    std::cout << archive[0].owner << " has " << archive[0].messages.size()
              << " messages\n";

    auto token = std::make_unique<int>(42);
    auto taken = std::move(token);
    std::cout << std::boolalpha << "token empty: " << (token == nullptr)
              << ", taken holds " << *taken << '\n';
}

Quick quiz 1 / 3

After std::string t = std::move(s);, which use of s is always safe?

Quick quiz 2 / 3

const std::string title = "Report"; std::string copy = std::move(title); What happens?

Quick quiz 3 / 3

A class has the members std::string name; and std::vector<int> scores;. Which special member functions should you write?

What to remember

  • A copy duplicates an object's data; a move hands over its internal buffer and is usually far cheaper.
  • std::move is only a cast to an rvalue; the move happens in the receiving constructor or assignment, and never for a const object.
  • A moved-from object is valid but unspecified: assign it or let it be destroyed, but do not rely on its contents.
  • Rule of zero: build classes from self-managing members and write no special members; rule of five: if you write one, consider all five.

C++ Core Guidelines — Standard C++ Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.