Topic 12 of 27 · Expert
Move Semantics & Rvalue References
lvalues vs rvalues, std::move, perfect forwarding.
Concept
An lvalue has a name and address; an rvalue is a temporary. An rvalue reference (T&&) binds to temporaries so their resources can be stolen instead of copied.
A move constructor transfers ownership (pointer swap) and leaves the source in a valid but unspecified state. Mark it noexcept so vector uses it when growing.
std::move just casts to an rvalue; it doesn't move anything itself. std::forward preserves value category in templates (perfect forwarding).
Code (C++20)
#include <string>
#include <utility>
#include <vector>
class Doc {
std::vector<std::string> pages_;
public:
Doc() = default;
Doc(Doc&& o) noexcept : pages_(std::move(o.pages_)) {}
Doc& operator=(Doc&& o) noexcept { pages_ = std::move(o.pages_); return *this; }
void add(std::string p) { pages_.push_back(std::move(p)); }
};
template <typename T, typename... Args>
T make(Args&&... args) { return T(std::forward<Args>(args)...); }
int main() {
Doc a; a.add("intro");
Doc b = std::move(a); // moved, no deep copy
auto s = make<std::string>(5, 'x'); // "xxxxx"
}Remember
- std::move is only a cast.
- Move constructors should be noexcept.
- Don't use an object after moving except to assign/destroy it.
Interview questions
What is the benefit of move semantics?
Transferring resources from temporaries instead of deep-copying them, e.g. returning large vectors cheaply.
What is perfect forwarding?
Using T&& (forwarding reference) with std::forward so a template passes arguments on as lvalues or rvalues exactly as received.
Lesson test
Take an 8-question test on “Move Semantics & Rvalue References” — concepts, output prediction, bug spotting and interview questions.