liveBook · Manning

Std::move

As explained in C++ Concurrency in Action, Second Edition

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

`std::move` casts an expression to an rvalue reference, allowing a move operation to transfer ownership rather than copy it. A named object requires an explicit `std::move`; moving from a temporary happens implicitly. section 2.3 section 2.2

Transfer a thread

`std::thread t2 = std::move(t1);` transfers the thread associated with `t1` to `t2`, leaving `t1` without an associated thread. By contrast, initializing `t1` from a temporary `std::thread` needs no explicit `std::move`. section 2.3

Moving into a `std::thread` that already manages a thread is not a safe way to discard it: move assignment calls `std::terminate()` in that case. Join or detach the existing thread before replacing its owner. section 2.3

void some_function();
void some_other_function();
std::thread t1(some_function);
std::thread t2=std::move(t1);
t1=std::thread(some_other_function);
std::thread t3;
t3=std::move(t2);
t1=std::move(t3);          #1

Trace ownership among three `std::thread` objects and see why the final assignment terminates the program. section 2.3

How C++ Concurrency in Action, Second Edition covers it

How deep it goes
Works through named and temporary sources, ownership changes, and a thread-assignment failure, without detailing move internals.
Examples
Uses thread transfers among three objects and transfers a `std::unique_ptr` into a thread function.
What you can do after
Apply it via `std::move` to transfer ownership from named objects and recognize when thread replacement would terminate.
How it connects
Connects move semantics to `std::thread`, `std::unique_ptr`, move constructors, and move assignment operators.

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 C++ Concurrency in Action, Second Edition. The section links point to the parts of the book it draws on.