Move semantics (C++11) solve the problem of unnecessary deep copies of temporary objects (rvalues). By "stealing" resources like heap-allocated buffers, we achieve constant time "copying".
Rvalue References (&&)
While an lvalue reference (T&) binds to an object with a name, an rvalue reference (T&&) binds to a temporary object that is about to expire.
void process(std::string& lval) { /* copy */ }
void process(std::string&& rval) { /* move */ }
std::string s = "hello";
process(s); // Calls lvalue version
process("world"); // Calls rvalue version
process(std::move(s)); // Calls rvalue version, s is moved-from
The Rule of Five
To support move semantics, your class should implement:
- Destructor
- Copy Constructor
- Copy Assignment
- Move Constructor
- Move Assignment
std::forward (Perfect Forwarding)
Used in value-neutral generic code (templates) to forward arguments to another function while preserving their lvalue/rvalue-ness.