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.
0 of 10 checks passed
Your progress is saved on this device.