Skip to content

Copy and move semantics

Difficulty: Intermediate

Key concepts

  • copy constructor
  • copy assignment
  • move constructor
  • move assignment
  • rvalue
  • std::move
  • moved-from state
  • copy elision
  • noexcept
  • What copying and moving an object each do, and why moving exists.
  • Which statements copy, which move, and which do neither.
  • Why std::move does not move anything by itself.
  • What you may do with an object after it has been moved from.
  • Why move operations should be noexcept, and what containers do when they are not.

The value semantics lesson showed that C++ copies objects by default. A copy of an object that owns memory, such as a std::vector or a std::string, allocates new memory and duplicates every element. That is exactly right when both objects are still needed afterwards.

Often, though, the source is about to disappear: it is a temporary, or a local variable that is never used again. Duplicating its contents and then destroying the original is wasted work. Move semantics lets the new object take over the source’s resources instead: for a vector, that means copying its internal pointers and clearing the source’s. No elements are touched, and nothing is allocated.

To see which happens when, this lesson uses a Buffer that owns a block of bytes and prints a line every time it is copied or moved:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

buffer.hpp
// A named block of bytes that reports every copy and move. Each of the
// four copy and move operations below does the real work (duplicate or
// take over the name and bytes) and then calls note(), which adds 1 to a
// global counter (counts.copies or counts.moves, declared just above this
// class) and, if the global flag `trace` is true, prints a line such as
// " copy-construct a" naming the object it has just filled in.
// Invariant: size() is the number of bytes owned. A moved-from Buffer is
// empty (no name, size 0); it may be assigned a new value or destroyed.
class Buffer {
public:
// bytes_(size) makes a vector of `size` bytes, all zero ('\0'). Note the
// round brackets: bytes_{size} would instead ask for a vector holding one
// element, `size` squeezed into a char, which is a narrowing error.
Buffer(std::string name, std::size_t size) : name_(std::move(name)), bytes_(size) {}
// Copy: the new object gets its own duplicate of the bytes.
// Copying the std::vector allocates a new block and copies every byte,
// so afterwards changing one Buffer never affects the other.
Buffer(const Buffer& other) : name_(other.name_), bytes_(other.bytes_) {
note("copy-construct", counts.copies);
}
// Copy assignment: `*this` already exists and already owns bytes; it is
// made into a duplicate of `other`.
Buffer& operator=(const Buffer& other) {
// Copy into locals first: if allocation throws, *this is unchanged.
std::string name = other.name_;
std::vector<char> bytes = other.bytes_;
// Moving the locals into the members cannot throw. Each member's old
// contents are released by its own assignment.
name_ = std::move(name);
bytes_ = std::move(bytes);
note("copy-assign", counts.copies);
// Returning a reference to this object is the convention for `=`;
// it is what makes `x = y = z` work.
return *this;
}
// Move: take over other's bytes, and leave other empty. No allocation,
// so it cannot fail, and noexcept says so.
// `Buffer&&` (an rvalue reference) binds only to a temporary or to an
// object passed with std::move: one the caller lets us empty.
// std::exchange(other.name_, {}) puts an empty value (`{}`) into
// other.name_ and returns what it held before; that old value
// initialises our name_. The same happens to the bytes.
Buffer(Buffer&& other) noexcept
: name_(std::exchange(other.name_, {})), bytes_(std::exchange(other.bytes_, {})) {
note("move-construct", counts.moves);
}
// Self-move (a = std::move(a)) is harmless: exchange reads the old value
// before it writes the new one.
// Move assignment: our current name and bytes are released when the
// members are assigned, and other's are taken over in their place.
Buffer& operator=(Buffer&& other) noexcept {
name_ = std::exchange(other.name_, {});
bytes_ = std::exchange(other.bytes_, {});
note("move-assign", counts.moves);
return *this;
}
// Written out only to show all five; the members free themselves.
~Buffer() = default;
[[nodiscard]] const std::string& name() const noexcept { return name_; }
[[nodiscard]] std::size_t size() const noexcept { return bytes_.size(); }
// Throws std::out_of_range if index >= size().
// vector::at checks the index (unlike []), which is where the throw
// comes from.
void set(std::size_t index, char value) { bytes_.at(index) = value; }
[[nodiscard]] char get(std::size_t index) const { return bytes_.at(index); }
private:
// `counter` is a reference (int&), so ++counter changes the global
// counter that was passed in, not a copy of it. The function is const
// because it does not change this Buffer, only the global totals.
void note(const char* what, int& counter) const {
++counter;
if (trace) std::cout << " " << what << ' ' << name_ << '\n';
}
std::string name_;
std::vector<char> bytes_;
};
How this code works: Buffer's copy assignment and move constructor

Copy assignment, b = c; (as in statement 3 below, where c is named "a" and holds 1024 bytes):

  1. name and bytes are local copies of c’s name and bytes. This is the only step that allocates, so it is the only step that can throw. If it does, the locals are destroyed and b has not been touched yet.
  2. The locals are moved into b’s members. Each assignment releases what the member held before (b’s old bytes), and moving cannot throw.
  3. note adds 1 to counts.copies and prints copy-assign a, because b’s name is now "a".
  4. return *this; hands back b itself, so assignments can be chained.

Doing the risky work first and then committing it with operations that cannot fail means b ends up either fully updated or unchanged, never half-copied.

Move constructor, Buffer c = std::move(a); (statement 2):

  1. std::move(a) lets a bind to Buffer&&, so this constructor is chosen.
  2. std::exchange(other.name_, {}) returns "a" and leaves a.name_ empty; that "a" becomes c.name_.
  3. std::exchange(other.bytes_, {}) does the same with the vector: c.bytes_ takes over the block of 1024 bytes, and a.bytes_ is left empty. Moving a vector only moves its internal pointers, so no byte is copied.
  4. note adds 1 to counts.moves and prints move-construct a.
After Buffer c = std::move(a); name() size()
a "" 0
c "a" 1024

a is still a valid object, and its destructor still runs at the end of main; it just has nothing left to free.

A class has four operations for this, plus the destructor; together with the default constructor they are called its special member functions:

  • Copy constructor Buffer(const Buffer&): creates a new object as a copy.
  • Copy assignment Buffer& operator=(const Buffer&): makes an existing object a copy of another.
  • Move constructor Buffer(Buffer&&): creates a new object by taking over another’s resources.
  • Move assignment Buffer& operator=(Buffer&&): makes an existing object take over another’s resources, after releasing its own.

Buffer&& is an rvalue reference: a reference that binds only to objects the caller has said may be taken over. Buffer writes all four so that it can print, and so that its moved-from state is exactly “empty”. The versions the compiler generates would copy and move correctly too, but would not guarantee that state. The next lesson explains when you should write them yourself (rarely).

Before and after Buffer c = std::move(a): the bytes change owner; nothing is copied
Text description of the diagram

Before the move, a owns a block of 1024 bytes, and c does not exist yet. After Buffer c = std::move(a);, c owns the same block of 1024 bytes, which was not copied or reallocated, and a is left empty, with size 0, still a valid object.

Diagram source (Mermaid)
flowchart LR
subgraph before ["Before"]
  A1["a: name a, size 1024"] --> M1[("1024 bytes")]
  C1["c: not yet constructed"]
end
subgraph after ["After"]
  A2["a: moved-from, empty, size 0"]
  C2["c: name a, size 1024"] --> M2[("the same 1024 bytes")]
end
before --> after

The compiler chooses between the copy and move operations by looking at the expression that provides the value:

  • An lvalue is an expression that refers to an existing object, such as a variable a. The object may be used again afterwards, and taking it over would surprise the code that uses it, so the copy operation is chosen.
  • An rvalue is a temporary, such as the result of make_buffer(...), or an object explicitly marked with std::move. Nobody can use it afterwards (or the programmer has promised not to), so the move operation is chosen.

(The standard has a few more value categories; for choosing between copy and move, these two ideas are enough.)

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// Each numbered line prints the statement, and then Buffer prints which
// operation (if any) the statement ran.
Buffer a("a", 1024); // the ordinary constructor: prints nothing
std::cout << "1. Buffer b = a;\n";
Buffer b = a; // a is an lvalue: copy
std::cout << "2. Buffer c = std::move(a);\n";
Buffer c = std::move(a); // std::move(a) is an rvalue: move
// a still exists, but the move emptied it: its size is now 0.
std::cout << " a.size() = " << a.size() << ", c.size() = " << c.size() << '\n';
std::cout << "3. b = c;\n";
b = c; // assignment from an lvalue: copy-assign
std::cout << "4. b = make_buffer(\"report\", 64);\n";
b = make_buffer("report", 64); // assignment from a temporary: move-assign
std::cout << "5. Buffer d = make_buffer(\"log\", 16);\n";
Buffer d = make_buffer("log", 16); // initialized directly: nothing printed
std::cout << "6. Buffer e = std::move(frozen); (frozen is const)\n";
const Buffer frozen("frozen", 8);
Buffer e = std::move(frozen); // a const object cannot be moved from: copy
Expected output
1. Buffer b = a;
copy-construct a
2. Buffer c = std::move(a);
move-construct a
a.size() = 0, c.size() = 1024
3. b = c;
copy-assign a
4. b = make_buffer("report", 64);
move-assign report
5. Buffer d = make_buffer("log", 16);
6. Buffer e = std::move(frozen); (frozen is const)
copy-construct frozen
7. a vector that grows
copies: 1, moves: 4

Statement by statement:

  1. Buffer b = a; copies, because a is a named object.
  2. Buffer c = std::move(a); moves. Afterwards a is empty and c has the 1024 bytes.
  3. b = c; is copy assignment: b already exists, and c is named.
  4. b = make_buffer(...) is move assignment: the function’s result is a temporary, so b takes over its bytes.
  5. Buffer d = make_buffer(...) prints nothing at all. Since C++17, when a function returns a temporary (a prvalue) and that value initializes an object, the object is constructed directly in its final place. This is called guaranteed copy elision: there is no copy or move to perform.
  6. Buffer e = std::move(frozen); copies, even though it says std::move. The next section explains why.

std::move(x) does not move anything. It is a cast that turns x into an rvalue, which says “the caller allows x to be taken over”. Whether anything is moved depends on which constructor or assignment operator is then chosen.

For a const object, the result is a const Buffer&&. The move constructor takes a non-const Buffer&&, because moving changes the source (it empties it), so it cannot accept a const object. The copy constructor, which takes const Buffer&, can, so it is chosen. The code compiles, and silently copies. GCC 11 and Clang 14 give no warning for this with this site’s warning flags.

So: std::move on a const object copies. Do not make an object const if you intend to move from it later, and do not rely on std::move alone to prove that nothing was copied.

After Buffer c = std::move(a);, the object a still exists, and its destructor will still run. What state is it in?

  • Standard library types leave a moved-from object in a valid but unspecified state. It is still a real object with its invariants intact, so you can destroy it, assign a new value to it, or call functions that have no preconditions (such as size() or empty()), but you must not assume what value it holds.
  • Your own types decide. Buffer documents its moved-from state in the invariant comment (“empty: no name, size 0”), and its move operations make it so with std::exchange, which replaces a member with a new value and returns the old one.

The safe rule for code that uses a moved-from object: only destroy it or assign a new value to it, unless its type documents more. Code that moves from a variable and then reads it is usually a bug, and the test below checks that a moved-from Buffer can be reused by assignment.

You rarely need to write std::move. Moves happen without it in two common cases:

  • Temporaries: b = make_buffer("report", 64); moves.
  • Returning a local variable or parameter: return result; is treated as an rvalue even though result is a name. For a non-const local, the compiler either constructs result directly in the caller’s object (an optimization compilers usually make, but are not required to, and never for parameters), or moves it. A const local is copied, for the reason in the previous section.

Write std::move when you pass on a named object that you will not use again, as in the sink parameter from the value semantics lesson: Member(std::string name) : name_(std::move(name)) {}.

Do not write return std::move(result); for a local variable. It prevents the compiler from constructing result directly in place and forces a move. GCC 11 and Clang 14 both warn about it (-Wpessimizing-move, enabled by -Wall), and this site’s builds treat warnings as errors.

When a std::vector runs out of room, it allocates a larger block and transfers its elements there. It promises that if anything throws during this growth, the vector is left unchanged. That promise decides between moving and copying:

  • If a move could throw halfway, some elements would already have been moved out of the old block, and the vector could not restore them. So if the move constructor is not noexcept (and the type can be copied), the vector copies the elements instead. A failed copy leaves the originals untouched.
  • If the move constructor is noexcept, the vector moves.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
std::cout << "7. a vector that grows\n";
lld::copymove::trace = false; // stop printing; only count from here on
counts = {}; // reset both counters to 0
std::vector<Buffer> shelf;
// reserve(2) sets aside room for two Buffers (creating none), so the
// first two push_backs fit and the third forces the vector to grow.
shelf.reserve(2);
shelf.push_back(d); // copy
shelf.push_back(std::move(e)); // move
// Growing: the vector allocates a bigger block, moves the new "x" and
// the two old elements into it, and frees the old block. Buffer's moves
// are noexcept, so the vector is allowed to move rather than copy.
shelf.push_back(Buffer("x", 8)); // move, and growing moves the first two
std::cout << " copies: " << counts.copies << ", moves: " << counts.moves << '\n';

The last line of the output above counts what happened: one copy (push_back(d)), and four moves: push_back(std::move(e)), the temporary Buffer("x", 8), and the two existing elements transferred when the third element did not fit. Had the move constructor not been noexcept, the two transfers would have been copies, each duplicating a block of bytes.

Mark a move constructor and move assignment noexcept whenever they cannot fail, which is the usual case: they only transfer pointers and do not allocate. The compiler-generated moves are noexcept automatically when every member’s moves are.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_buffer.cpp
// LLD_TEST(name) defines one test; LLD_CHECK(condition) fails it if the
// condition is false; LLD_CHECK_EQ(actual, expected) fails it if the two
// values differ, and prints both. Each test first sets trace to false so
// the copies and moves are counted but not printed.
// Changing the copy must leave the original alone: each owns its bytes.
LLD_TEST(a_copy_is_independent) {
lld::copymove::trace = false;
Buffer original("a", 4);
Buffer copy = original;
copy.set(0, 'x');
LLD_CHECK_EQ(original.get(0), '\0'); // new bytes start as zero
LLD_CHECK_EQ(copy.get(0), 'x');
LLD_CHECK_EQ(original.size(), copy.size());
}
// After a move, the target has the bytes and name, the source is in its
// documented empty state, and the source can still be given a new value.
LLD_TEST(a_move_transfers_and_leaves_the_source_empty) {
lld::copymove::trace = false;
Buffer source("a", 4);
source.set(1, 'y');
Buffer target = std::move(source);
LLD_CHECK_EQ(target.get(1), 'y');
LLD_CHECK_EQ(target.name(), std::string("a"));
// std::size_t{0} makes the expected value the same type as size().
LLD_CHECK_EQ(source.size(), std::size_t{0}); // the documented moved-from state
LLD_CHECK(source.name().empty());
source = Buffer("reused", 2); // a moved-from object can be given a new value
LLD_CHECK_EQ(source.size(), std::size_t{2});
}
// std::move on a const object picks the copy constructor: one copy, no
// moves, and the const source keeps its 4 bytes.
LLD_TEST(std_move_on_a_const_object_copies) {
lld::copymove::trace = false;
counts = {};
const Buffer frozen("f", 4);
Buffer other = std::move(frozen);
LLD_CHECK_EQ(counts.copies, 1);
LLD_CHECK_EQ(counts.moves, 0);
LLD_CHECK_EQ(frozen.size(), std::size_t{4});
}
// When the vector grows, it relocates the old element with the move
// constructor, not the copy constructor, because the move is noexcept.
LLD_TEST(a_growing_vector_moves_because_the_move_is_noexcept) {
// static_assert is checked by the compiler: if Buffer's move
// constructor were not noexcept, this file would not compile.
static_assert(std::is_nothrow_move_constructible_v<Buffer>);
lld::copymove::trace = false;
std::vector<Buffer> shelf;
shelf.reserve(1);
// emplace_back passes ("first", 4) to Buffer's constructor and builds
// the element in place inside the vector, so no copy or move is needed.
shelf.emplace_back("first", 4);
counts = {}; // count only what the next line does
shelf.emplace_back("second", 4); // reallocates: the first element is relocated
LLD_CHECK_EQ(counts.copies, 0);
LLD_CHECK_EQ(counts.moves, 1);
}

The static_assert checks at compile time that the move constructor is noexcept, so a change that dropped it would fail the build rather than silently make vectors copy.

  • Most classes need nothing. If a class’s members are standard types (strings, containers, smart pointers), the generated copy and move operations are correct and efficient. The next lesson calls this the Rule of Zero.
  • Write std::move when handing on a named object you are finished with, especially into a member or a container.
  • Think about copies when an object is large and copied often, such as in a loop or a frequently called function. Measure before rewriting code for this.
  • Delete copying for types whose objects must be unique, such as the RAII lesson’s File.
  • Using an object after moving from it. Its value is unspecified unless its type says otherwise. Assign it a new value first.
  • std::move on a const object. It copies silently.
  • return std::move(local); It prevents direct construction in the caller.
  • A move constructor without noexcept. Containers copy instead of moving when they grow.
  • A move that leaves the source invalid. The source’s destructor still runs, so it must still be safe to destroy; a move must not leave, for example, a pointer that both objects will delete.

New requirement: “Buffers can be very large, and copying one by accident must be impossible; transferring one between components must stay cheap.”

Delete Buffer’s copy constructor and copy assignment, and keep the moves. Every accidental copy, such as passing a Buffer by value without std::move, becomes a compile error that points at the line, while std::move and returning from a function keep working. If some code genuinely needs a duplicate, give the class an explicit Buffer clone() const function, so every expensive copy is visible in the source.

Exercise: Predict copies and moves

Using the Buffer class above, predict which special member function each numbered statement calls, if any. step(n) just prints (n).

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

exercise.cpp
// Three helpers, which differ only in how the Buffer goes in or comes out:
// make returns a new 8-byte Buffer built in its return statement, inspect
// takes a const reference, and keep takes its parameter by value.
Buffer make(std::string name) { return Buffer(std::move(name), 8); }
std::size_t inspect(const Buffer& buffer) { return buffer.size(); }
std::size_t keep(Buffer buffer) { return buffer.size(); }
// Each step(n) prints (n) before statement n, so any line Buffer prints
// below (n) belongs to that statement.
void run() {
step(1); Buffer a = make("a");
step(2); inspect(a);
step(3); keep(a);
step(4); keep(std::move(a));
Buffer b("b", 8);
step(5); b = make("m");
const Buffer c("c", 8);
step(6); Buffer d = c;
step(7); Buffer e = std::move(c);
step(8); Buffer f = std::move(d);
}
Show the explained answer
Expected output
(1)
(2)
(3)
copy-construct a
(4)
move-construct a
(5)
move-assign m
(6)
copy-construct c
(7)
copy-construct c
(8)
move-construct c
  1. Nothing. make returns a temporary, and guaranteed copy elision constructs it directly as a.
  2. Nothing. inspect takes a const Buffer&, so no new object is created.
  3. Copy constructor. keep takes its parameter by value, and a is an lvalue.
  4. Move constructor. std::move(a) makes it an rvalue, so the parameter is move-constructed. a is now empty, and is not used again.
  5. Move assignment. b already exists, and the result of make is a temporary.
  6. Copy constructor. c is an lvalue.
  7. Copy constructor. c is const, so std::move(c) is a const Buffer&&, which cannot bind to the move constructor.
  8. Move constructor. d is not const. It prints c because d was copied from c in statement 6 and so has the name c.
  • Copying duplicates an object’s resources; moving transfers them and leaves the source valid but (unless documented) unspecified.
  • Named objects (lvalues) are copied; temporaries and std::moved objects (rvalues) are moved; a returned temporary initializing an object is neither.
  • std::move is only a cast. On a const object, it results in a copy.
  • After moving from an object, only destroy it or assign to it, unless its type documents more.
  • Make move operations noexcept, or containers will copy when they grow.