12.2 — Move semantics

📘 Chapter 12⏱ about 2 min read✍️ Beginner friendly
Read one box at a time. No rush.

Copying can be slow#

Copying an int is instant. Copying a std::vector with a million items means copying a million items.

C++
std::vector<int> big(1'000'000, 7);std::vector<int> copy { big };   // copies all 1,000,000 numbers

Moving instead of copying#

Often we don't need the old one any more. Then we can move it: hand over the insides instead of copying them. Like giving someone your box instead of filling a new one item by item.

C++
#include <utility> std::vector<int> big(1'000'000, 7);std::vector<int> taken { std::move(big) };   // super fast std::cout << taken.size() << '\n';   // 1000000std::cout << big.size() << '\n';     // usually 0 — big was emptied
Watch out

After std::move(x), don't use x's value again. It is still valid (you can give it a new value), but what's inside is unknown.

Where moves happen for free#

You often get moves without writing anything:

C++
std::vector<std::string> makeNames(){    std::vector<std::string> names { "Ana", "Ben" };    return names;   // moved (or even skipped entirely), not copied}
Key idea

Returning a local variable from a function is cheap. You do not need to avoid returning vectors or strings.

unique_ptr can only move#

A std::unique_ptr has exactly one owner, so it can't be copied — only moved:

C++
auto a { std::make_unique<int>(5) };auto b { a };              // error: can't copyauto c { std::move(a) };   // fine: c owns it now, a is empty
Tip

As a beginner, you rarely need to write std::move. Knowing that it exists helps you read other people's code and understand error messages.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.