liveBook · Manning

Std::move

As explained in 100 C++ Mistakes and How to Avoid Them

std::move is a C++ standard library function template that casts an expression to an rvalue reference to enable move operations.

Mistake: treating std::move as the operation that moves an object. It actually casts an lvalue to an rvalue reference, making the expression eligible for move construction or move assignment instead of ordinary copying. section 2.1 section 2.8

After transfer, treat the source as drained and do not use it unless it is reinitialized. Move constructors and move-assignment operators should neutralize transferred pointers, commonly by setting them to nullptr. section 2.1 section 2.8

Transfer a Page without copying its resources

A copy such as `Page p2 = p1;` duplicates the body and then deletes data from the source in the problematic implementation. The corrected version supplies `Page(Page&& o)`, transfers the pointers, clears `o.headers` and `o.body`, and uses `Page p2 = std::move(p1);`. The transfer can therefore use move semantics rather than a costly copy.

Transfer exclusive ownership with unique_ptr

Use `auto b2 = std::move(b1);` to transfer a `Buffer` held by `std::unique_ptr`. The receiving owner takes the resource, while the original owner should be treated as unusable until reinitialized. section 2.8

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Explains the cast and moved-from state, then demonstrates pointer transfer in move construction and unique_ptr ownership.
Examples
Uses Page pointer transfer and Buffer ownership transfer through unique_ptr.
What it assumes
Assumes familiarity with C++ objects, pointers, copying, and ownership while explaining lvalues, rvalues, and move eligibility.
What you can do after
Apply std::move to eligible lvalues and handle moved-from objects cautiously during resource ownership transfers.
How it connects
Connects std::move with move semantics, rvalue references, move constructors, move assignment, unique_ptr, and exclusive ownership.

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 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.