12.2 — Move semantics
Copying can be slow#
Copying an int is instant. Copying a std::vector with a million items means copying a million items.
std::vector<int> big(1'000'000, 7);std::vector<int> copy { big }; // copies all 1,000,000 numbersMoving 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.
#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 emptiedAfter 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:
std::vector<std::string> makeNames(){ std::vector<std::string> names { "Ana", "Ben" }; return names; // moved (or even skipped entirely), not copied}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:
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 emptyAs a beginner, you rarely need to write std::move. Knowing that it exists helps you read other people's code and understand error messages.
Tip: press ← / → to move between lessons, / to search.