C++ · Advanced level

Advanced level · Module 2: Modern Memory Management · Lesson 4 of 4

Move Semantics and the Rule of Five

Make types cheap to move, understand rvalue references and know when to write the five special member functions.

In this lesson you will

  • Explain lvalues, rvalues and std::move
  • Implement move operations and apply the rule of five or zero

Key concepts

rvalue reference &&std::movemove constructor / move assignmentrule of five

The lesson

Moving transfers resources instead of copying them. Returning a large std::vector from a function, or inserting a temporary std::string into a container, moves its internal buffer rather than copying every element.

std::move(x) does not move anything by itself; it casts x to an rvalue so that a move constructor or move assignment can be chosen. After a move, the source is valid but unspecified — only assign to it or destroy it.

If a class manages a resource directly and needs a custom destructor, it needs all five special members: destructor, copy constructor, copy assignment, move constructor and move assignment (mark the moves noexcept). Better still, follow the rule of zero by holding resources in standard types.

Step by step

  1. Add printing to the copy and move constructors of a test class.
  2. Return it from a function and push it into a vector; observe moves.
  3. Use std::move to move a local into a container.
  4. Implement noexcept move operations for a resource-owning class.

Practice activity

Write a class that owns a large buffer, implement the rule of five and show with timing that moves are far cheaper than copies.

Expected result: Moves are measured to be much faster than copies, and the class passes copy and move tests under sanitizers.

Check your understanding

  1. What does std::move actually do?

    Show answer

    Casts its argument to an rvalue so move operations can be selected.

  2. Why mark move operations noexcept?

    Show answer

    Containers such as std::vector only use moves during reallocation if they cannot throw.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.