Skip to content

Chapter 29 of 31

Move Semantics

Understand value categories, move operations, forwarding, and moved-from states.

42 minutes 10 quick checksBy Subha Prasad
Lesson 29 of 31Course navigation

Lesson content

Read, practise, then check your understanding

Move semantics let an object transfer resources from an expiring source instead of copying them. An lvalue has identity and persists; an rvalue is a temporary or object treated as expiring. An rvalue reference uses T&&.

#include <string>
#include <utility>
#include <vector>

std::string source{"large payload"};
std::vector<std::string> messages;
messages.push_back(std::move(source));
// source is valid but its value is unspecified

std::move does not move anything by itself; it casts to an rvalue category so overload resolution can select a move constructor or assignment operator. Use the source only for operations valid without knowing its prior value, such as assigning or destroying it.

Move-aware types

A resource-owning move constructor transfers handles and leaves the source destructible. Mark move operations noexcept when true, because containers may otherwise copy during reallocation to preserve strong exception safety. Prefer the Rule of Zero; standard members already implement correct moves.

Copy elision often constructs a returned local directly at the destination, so return std::move(local); can inhibit optimization and should usually be return local;. A forwarding reference in a deduced context preserves lvalues and rvalues with std::forward<T>. Perfect forwarding belongs in generic wrappers and factories, not ordinary code. Moving const objects usually copies because a move normally needs to modify its source.

Knowledge check

Answer every question correctly to complete this chapter.

What does std::move do by itself?
What parameter type identifies an rvalue reference to T?
What must a moved-from standard object remain?
Why can moving a vector be cheap?
What special member accepts T&&?
Why mark a move constructor noexcept when correct?
What is perfect forwarding for?
What is copy elision?
Should code routinely std::move a local in return?
What rule reduces manual special-member code?

0 of 10 checks passed

Your progress is saved on this device.