C++ / CHAPTER 11

Move operations and valid remaining state

Advanced

Treat moving as permission to transfer, not guaranteed destruction.

By the end of this chapter

  • Distinguish std::move from an operation
  • Use moved-from standard objects safely
  • Maintain independent destination ownership

The idea

std::move casts an expression so overload resolution can select a move operation. It does not itself transfer resources, erase a value, or run a destructor. The receiving constructor or assignment performs whatever move behavior its type defines. Some types may copy instead, and an optimizing implementation need not have the internal behavior you imagined.

A moved-from standard-library object remains valid but its value is generally unspecified unless the type documents a stronger guarantee. Destroying it or assigning a new value is safe; asserting that a moved-from string must be empty is not portable. Keep the destination’s required value separate from assumptions about the source. Prefer ordinary value and RAII types so their move rules manage resources without hand-written ownership transfers.

C++ example
#include <iostream>
#include <string>
#include <utility>
int main() {
  std::string source = "report";
  std::string destination = std::move(source);
  source = "new";
  std::cout << destination << ' ' << source;
}
Result
report new

The destination receives the original text; assigning a new value to the valid moved-from source is supported.

Try it yourself

Transfer a vector into another owner, then explicitly reset and reuse the source without inspecting its unspecified old value.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What does evaluating std::move(value) itself do?