Skip to content
Tutorials Center
My learning

Topics

Lesson 75 of 171 ยท Object-Oriented Programming

Move Semantics

Learn C++ move semantics - lvalues and rvalues, rvalue references, std::move, move constructors and assignment, noexcept moves in std::vector, and moved-from objects.

Copying a std::vector with a million elements allocates new memory and copies a million values. That's the right thing when you need two independent vectors. But very often the source is about to disappear anyway: it's a temporary returned from a function, or a local variable you'll never use again. Copying it and then destroying the original is pure waste. It would be far cheaper to steal its buffer: take the pointer, leave the source empty, done.

That's what move semantics (C++11) gives you. A move transfers an object's resources to another object instead of duplicating them, usually by copying a few pointers. The standard library uses it everywhere: returning containers by value, growing a std::vector, sorting strings, passing std::unique_ptr around. In this lesson you'll learn how C++ decides when it may move (lvalues vs rvalues), what rvalue references and std::move really are, how to write a move constructor and move assignment, why moves should be noexcept, and what you may do with an object after it has been moved from.

lvalues and rvalues

Every expression has a value category. You only need two ideas to understand moves:

  • An lvalue is something with an identity that persists: a named variable, v[3], *ptr. You can take its address. It's still there after the expression ends, so stealing from it would surprise its owner.
  • An rvalue is a temporary that's about to vanish: make_vector(), a + b, a literal like 42, std::string{"hi"}. Nobody else can see it, so stealing from it is safe.

(The standard splits these further into prvalues, xvalues and glvalues. std::move(x) produces an xvalue: an object with an identity that you've declared you are done with. For everyday code, "rvalue" covers both.)

rvalue references

A plain reference T& binds only to lvalues (and const T& binds to everything). An rvalue reference, written T&&, binds only to rvalues. That lets you overload a function: one version for objects you must leave intact, one for objects you may plunder.

C++ Overloading on lvalues and rvalues

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The last line is the most important rule of this lesson: a named rvalue reference is an lvalue. Inside a function with a std::string&& s parameter, s has a name and can be used many times, so the compiler treats it as an lvalue. If you want to move from it, you must say so again with std::move(s).

std::move doesn't move

Despite the name, std::move (in <utility>) does nothing at run time. It's a cast: std::move(x) is roughly static_cast<T&&>(x). It changes the value category of the expression, which changes which overload is picked. The actual moving happens in the move constructor or move assignment that gets selected, if any.

Two consequences:

  • std::move on a type without move operations simply selects the copy operations. It's never an error, just a copy.
  • std::move on a const object yields const T&&, which can't bind to T&&, so you silently get a copy. Don't make objects const if you intend to move from them.

Writing a move constructor and move assignment

Here's a buffer class like the one from Copy Constructors and Copy Assignment, now with move operations. A move constructor takes T&&, steals the source's pointer, and sets the source to an empty but valid state, so its destructor is harmless.

C++ A class with move operations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

std::exchange(x, new_value) (from <utility>) sets x to new_value and returns the old value, which is exactly "take it and leave something behind". After the move, a is an empty buffer whose destructor deletes nullptr, which is a safe no-op.

In make_buffer, return local; doesn't print "move" at all: GCC applied NRVO and built local directly in d. When the compiler can't elide, returning a local variable automatically moves it. Never write return std::move(local);: it blocks elision, and GCC warns about it with -Wpessimizing-move (enabled by -Wall).

noexcept moves and std::vector growth

When a std::vector runs out of capacity, it allocates a bigger block and transfers the old elements. Moving them is much cheaper than copying, but there's a catch. push_back promises the strong exception guarantee: if something throws, the vector is unchanged. If a move throws halfway, some elements have already been gutted, and the original can't be restored. So the vector only moves elements whose move constructor is noexcept (or that can't be copied at all). Otherwise it copies them, to be safe.

C++ noexcept decides whether vector moves or copies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Same number of transfers, but Risky pays for full copies on every reallocation. For a vector of large strings or buffers, that's the difference between fast and very slow. Rules of thumb:

  • Mark move constructors and move assignment noexcept. Stealing pointers can't fail, so it's an honest promise.
  • The compiler-generated move operations are noexcept automatically when every member's moves are.
  • std::move_if_noexcept is the tool the library uses for this decision; you'll rarely call it yourself.

See Exception Safety and noexcept for the guarantees in depth.

The moved-from state

After b = std::move(a), what is a? The standard's answer for library types is "valid but unspecified":

  • Valid: its invariants hold, it can be destroyed, and you may call operations that have no preconditions: assign a new value, clear(), size(), empty().
  • Unspecified: you can't assume what it contains. Don't read it expecting the old value, and don't call operations with preconditions, such as front() on a vector that might be empty.

Some types do specify the state: a moved-from std::unique_ptr or std::shared_ptr is guaranteed to be null.

C++ What is left after a move

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

When you write your own moves, leave the source in a state where the destructor and assignment work. "Empty" is the natural choice, as with Buffer above.

Using moves in everyday code

You'll write move constructors rarely; you'll use moves constantly. The common patterns:

Sink parameters. A function that stores its argument can take it by value and move it into place. Callers with an lvalue pay one copy, callers with an rvalue pay only moves:

C++ Pass by value, then move

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Moving into containers. v.push_back(std::move(item)) when you no longer need item; v.emplace_back(args...) to construct in place with no move at all.

Moving out of loops and swaps. std::swap and algorithms like std::sort and std::ranges::reverse move elements internally, which is why sorting a vector of strings doesn't copy text.

Move-only types. std::unique_ptr, std::thread, std::jthread and file streams can't be copied, but they can be moved: ownership moves from one variable to another. See Smart Pointers: std::unique_ptr.

Mistakes to avoid

  • return std::move(local); blocks copy elision. Just return local;.
  • Using an object after moving from it, other than reassigning or destroying it.
  • std::move on a const object, which copies.
  • Moving from something you still need, like a member variable in a const function or an element you'll read later.
  • Forgetting noexcept on hand-written moves, which makes std::vector copy.

In templates, T&& with a deduced T means something different: a forwarding reference that binds to both lvalues and rvalues, used with std::forward. That's covered in Variadic Templates and Fold Expressions.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Inside void store(std::string&& s), which expression lets you move s into a member?

    A named rvalue reference is an lvalue. Without std::move, member_ = s copies.
  2. 2. What does std::move(x) do at run time?

    std::move is a static_cast to an rvalue reference. The actual transfer happens only if a move constructor or move assignment is called with the result.
  3. 3. A class has a move constructor without noexcept and a normal copy constructor. What does std::vector do with its elements when it grows?

    If a throwing move failed halfway, the vector couldn't restore its old state. So it copies unless the move constructor is noexcept (or the type can't be copied).
  4. 4. const std::vector<int> a{1, 2, 3}; auto b = std::move(a); What is the result?

    std::move(a) yields const std::vector<int>&&, which can't bind to the move constructor's non-const rvalue reference, so the copy constructor is chosen.
  5. 5. Which statement about a moved-from std::string is correct?

    Library types are left valid but unspecified. You may destroy or reassign them and call operations without preconditions; don't rely on their contents.

Summary

  • A move transfers resources from an object that won't be needed again; it's usually a few pointer copies instead of a full deep copy.
  • lvalues have an identity and persist; rvalues are temporaries. T&& binds only to rvalues, so overloads can treat the two differently.
  • std::move is only a cast. A named rvalue reference is itself an lvalue, so you must std::move it again to move from it.
  • Write a move constructor and move assignment by stealing the source's resources (std::exchange helps) and leaving it empty but valid. Mark them noexcept, or std::vector will copy on growth.
  • Moved-from library objects are valid but unspecified: reassign or destroy them, don't read them. Moved-from smart pointers are null.
  • Return locals by plain return x;, take sink parameters by value and move them, and never std::move a const object expecting a move.

Next: The Rule of Zero, Three and Five, which ties copying, moving and destruction together into simple design rules.