Modern C++ • C++20 baseline
Value Categories, std::move, and Perfect Forwarding
Understand when expressions can be moved and forward generic arguments without changing their category.
std::move is a cast that enables overload resolution to select move operations; it does not move anything by itself. A named variable is an lvalue expression even if its declared type is an rvalue reference. Perfect forwarding with std::forward preserves the caller’s value category in a template.
Key points
- Do not use an object after moving from it except in ways its type documents as valid.
- Do not add std::move to a local return expression when it prevents copy elision.
Example
#include <string>
#include <utility>
void consume(std::string value);
template <typename T>
void relay(T&& value) {
consume(std::forward<T>(value));
}
What to expect
An lvalue string passed to relay is forwarded as an lvalue; a temporary string is forwarded as an rvalue.
Practice exercise
Trace the deduced T for an lvalue and a temporary. Explain why std::forward needs T.
Key idea: Use move and forward only when ownership or value-category transfer is part of the interface.