liveBook · Manning

Std::move

As explained in Learn C++ by Example

std::move is a C++ standard library utility that casts an expression to an rvalue reference to enable moving from it.

std::move casts an expression to an rvalue, enabling an overload or constructor that can move its contents instead of copying them. section 2.2.3 section 2.4

Use std::move with these rules in mind:

  • A named rvalue-reference parameter is an lvalue inside its function, so std::move casts it back to an rvalue. section 2.2.3
  • Moving can let vector operations select a move constructor and avoid unnecessary copies. section 2.2.3
  • After moving, the original value remains valid but has an unspecified state and is generally no longer useful. section 2.2.3
  • Prefer emplace_back when passing a temporary directly; std::move is useful when forwarding a named value. section 2.2.3

Forwarding a value inside push_back

A push_back overload taking T&& can call emplace_back(std::move(value)). Without the cast, the named value is treated as an lvalue and may select the copy constructor; with it, the rvalue overload can be selected. section 2.2.3

void push_back( T&& value ) {
   emplace_back(std::move(value));
}

The compact implementation shows how std::move forwards a named parameter to an emplacement operation. section 2.2.3

How Learn C++ by Example covers it

How deep it goes
Explains named rvalue references, overload selection, and moved-from states, but deliberately scratches only the surface of perfect forwarding.
Examples
Uses vector insertion, a triangle-row generator, push_back overloads, and direct emplace_back calls.
What it assumes
Assumes familiarity with vectors and function overloads while introducing rvalue references and move behavior.
What you can do after
Apply std::move to forward named values as rvalues and recognize when an operation may move instead of copy.
How it connects
Connects move semantics with rvalue references, perfect forwarding, move constructors, push_back, and emplace_back.

Also explained in

Compare how 3 books explain std::move →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.