Skip to content

Move semantics: stealing instead of copying

Deep diveConcept

Copying a vector of a million ints copies a million ints, yet returning one from a function costs almost nothing. The difference is whether the source will be used again. Here is how C++ tells the two apart with rvalues, what std::move really does, and why return v; is already the fast way.

01 A million ints, returned for free

Buf wraps a vector and prints a line whenever it is copied or moved. Watch the last line of main: make builds a million ints and returns them.

buf.cpp
#include <cstdio>
#include <utility>
#include <vector>
struct Buf {
std::vector<int> data;
explicit Buf(std::size_t n) : data(n) {}
Buf(const Buf& other) : data(other.data) { std::puts("copy"); }
Buf(Buf&& other) noexcept : data(std::move(other.data)) { std::puts("move"); }
};
Buf make() {
Buf b(1'000'000);
return b;
}
Shell
clang++ -std=c++17 -O2 buf.cpp -o buf && ./buf
Text
-- Buf b = a;
copy
-- Buf c = std::move(a);
move
a.data.size() = 0
-- Buf d = make();

A real run (Apple clang 17). The copy duplicated 4 MB of ints. The move printed move and left a empty. And make() printed nothing at all: no copy, no move. Three different costs, and the rest of this page explains each one.

02 A vector is a small handle and a big block

A std::vector<int> object is only a handle: a pointer to a heap block, plus the size and the capacity. On a typical 64-bit build that is 24 bytes, however many elements there are. The elements themselves live in the block.

One vector: the handle on the stack and the block it points to
v · the handle (24 bytes)
data 0x100
size 4
cap 4
Heap block at 0x100 (example address)
10
21
32
43

libstdc++ and libc++ actually store three pointers (begin, end, end of capacity). Drawing them as pointer, size and capacity says the same thing.

CopyA new block + n elementsAllocate, then copy every element. Both vectors stay usable and independent.
Move3 fieldsTake the pointer, size and capacity, then empty the source. The block never moves.

03 Copy and move, side by side

C++
{
std::vector<int> a = {1, 2, 3, 4};
std::vector<int> b = a; // copy
std::vector<int> c = std::move(a); // move
}
Copy, then move, then clean up
Step 1 of 7
Vector objects on the stack
datasizecapacity
a———
b———
c———
Heap blocks (example addresses)
free
free
  • just built
  • copied from
  • emptied by the move
  • same block, new owner
  • destroyed or freed
  • not built yet

Nothing is built yet. Three vectors will live on the stack; the heap has no blocks for them.

Stealing is only safe when nobody will look at the source again in a way that matters. A move leaves it valid but unspecified for most library types: you may destroy it or assign it a new value, but do not rely on what it holds. std::vector’s move constructor goes further and promises the source is empty, which is why a.data.size() printed 0.

04 rvalues: values nobody else can see

The compiler decides between copying and moving by looking at the value category of the expression you pass. An lvalue has a name or an address you can reach again, like s. An rvalue is a temporary, like the result of name() or s + "!": once the statement ends, nobody can refer to it, so taking its insides harms no one.

A parameter of type T&& (an rvalue reference) binds only to rvalues. Give a class two overloads, const T& for anything and T&& for rvalues, and overload resolution picks the stealing one exactly when it is safe.

over.cpp
#include <cstdio>
#include <string>
#include <utility>
void take(const std::string&) { std::puts("const std::string&"); }
void take(std::string&&) { std::puts("std::string&&"); }
std::string name() { return "Ana"; }
int main() {
std::string s = "Bo";
take(s); // a named variable
take(name()); // a temporary the function returned
take(s + "!"); // a temporary from an expression
take(std::move(s)); // a named variable, cast to rvalue
const std::string k = "Cy";
Text
const std::string&
std::string&&
std::string&&
std::string&&
const std::string&
Which overload each call picked (real run, clang 17)
ExpressionCategoryPicks
slvalueconst std::string&
name()rvalue (prvalue)std::string&&
s + "!"rvalue (prvalue)std::string&&
std::move(s)rvalue (xvalue)std::string&&
std::move(k), k constconst rvalueconst std::string&

05 std::move moves nothing

std::move(x) is only a cast: it is defined as static_cast<T&&>(x). It turns a named lvalue into an rvalue so that the && overload is chosen. The stealing, if any, happens later, inside the move constructor or move assignment that receives it.

That is why std::move on a const object quietly copies. The cast gives const T&&, which the move constructor (taking T&&) cannot accept, because it would have to change the source. The copy constructor’s const T& accepts it instead. With const Buf a(1'000'000);, the line Buf b = std::move(a); prints copy, and no compiler warning is given by default.

Inside a function, a parameter declared std::string&& s is itself an lvalue: it has a name. Passing s on copies it. Write std::move(s) at the point where you hand it over.

06 Why returning a big vector is cheap

Returning a local by value has three layers of protection, tried in order:

  • Guaranteed elision (C++17). return std::vector<int>(n); returns a temporary, and the language requires it to be built directly in the caller’s variable. There is nothing to copy or move.
  • Named return value optimisation (NRVO). return v; for a named local is allowed to be elided too. It is not guaranteed, but GCC, Clang and MSVC (with optimisation on) do it whenever every return path returns the same variable. This is why make() printed nothing.
  • Implicit move. When elision does not happen, a returned local is treated as an rvalue, so it is moved, not copied. Built with -fno-elide-constructors, the same buf.cpp prints move for make(), never copy.
Blocks elision
Buf make() {
Buf b(1'000'000);
return std::move(b);
}
// prints: move
Lets it elide
Buf make() {
Buf b(1'000'000);
return b;
}
// prints nothing

Writing return std::move(b); makes the expression an xvalue instead of the local’s name, and NRVO only applies to a plain name. You trade a free return for a move. Clang warns about this with -Wall:

Text
warning: moving a local object in a return statement prevents copy elision [-Wpessimizing-move]

07 Writing a move constructor of your own

Most classes should not write one. If every member already knows how to move (std::vector, std::string, std::unique_ptr), the compiler-generated move constructor moves each member and is correct. You need your own only when the class holds a raw resource directly, like this buffer.

buffer.h
#include <cstddef>
#include <utility>
class Buffer {
int* data_;
std::size_t size_;
public:
explicit Buffer(std::size_t n) : data_(new int[n]()), size_(n) {}
~Buffer() { delete[] data_; }
Buffer(const Buffer&) = delete;
Buffer& operator=(const Buffer&) = delete;
Buffer(Buffer&& other) noexcept
: data_(std::exchange(other.data_, nullptr)),

std::exchange(other.data_, nullptr) reads the old pointer and leaves nullptr behind in one go, so the source’s destructor has nothing to free. Mark both moves noexcept: containers such as std::vector move elements while growing only when the move cannot throw, and copy them otherwise. What std::vector does when it grows shows that rule in action.

08 When it bites

names.push_back(std::move(name)); log(name); // probably emptyUsing an object after moving from itThe value now lives in the vector. name is valid but its contents are unspecified (for std::string it is usually empty). Only assign to it or let it die. Clang-tidy’s bugprone-use-after-move flags this.
const std::string s = load(); v.push_back(std::move(s)); // copiesstd::move on a const objectA const source cannot be emptied, so the copy constructor is chosen and nothing tells you. Drop the const on anything you plan to move from.
return std::move(result);Moving a local on returnIt prevents NRVO and turns a free return into a move. Return the plain name; the language already moves it if it cannot elide.
template <class T> void wrap(T&& x) { use(std::move(x)); }T&& in a template is not an rvalue referenceWith a deduced T, T&& is a forwarding reference that also binds lvalues, and std::move would gut the caller’s variable. Use std::forward<T>(x) to keep the caller’s category.
Buffer(Buffer&& o) : data_(o.data_) {}A move that leaves the source owningBoth objects now point at the same block, and both destructors free it. A move must reset the source, and should be noexcept.

09 Check yourself

Question

What does std::move(v) do on its own, as a statement, if nothing receives the result?

Question

std::vector<int> f() { std::vector<int> v(1'000'000); return v; } What does the return usually cost with optimisation on?

Question

void keep(std::string&& s) { names.push_back(s); } Is s copied or moved into names?

10 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?