Move semantics lets an object take another object's resources instead of copying them. A move copies a pointer without reallocating the resource, so it is cheap no matter how large the data is:
std::vector#include <vector><int> a(1000000);
std::vector#include <vector><int> b = std::move#include <utility>(a);
b.size(); // 1000000
a.size(); // 0Lvalues and Rvalues
An lvalue is an expression that refers to an object whose address can be taken (e.g. a variable). An rvalue is a temporary value or literal whose address cannot be taken:
std::vector#include <vector><int> make() { return std::vector#include <vector><int>(1000000); }
int x = 5; // x is an lvalue, 5 is an rvalue.
make(); // Result is an rvalue.An rvalue reference (&&) only binds to rvalues. Since an rvalue is about to be destroyed, a function taking T&& can safely take its resources:
void take(std::vector#include <vector><int>& v); // Binds to lvalues.
void take(std::vector#include <vector><int>&& v); // Binds to rvalues.
std::vector#include <vector><int> v;
take(v); // Calls the lvalue overload.
take(make()); // Calls the rvalue overload.std::move
std::move#include <utility>() casts an lvalue to an rvalue, allowing the object to be moved. It is available from the utility header:
#include <utility>
std::vector#include <vector><int> v = {1, 2, 3};
take(std::move#include <utility>(v)); // Calls the rvalue overload.After a move, the moved-from object is in a valid but unspecified state. It can be destroyed or assigned a new value, but its contents shouldn't be relied on:
std::vector#include <vector><int> a = {1, 2, 3};
std::vector#include <vector><int> b = std::move#include <utility>(a);
a = {4, 5}; // OK, a is usable again.Note
Don't std::move#include <utility>() a function's return value as it disables named return value optimisation (NRVO).
Move Operations
A class supports moving by defining a move constructor and a move assignment operator, which take a T&&. Both should leave the moved-from object empty and be marked noexcept:
class Buffer {
public:
Buffer(Buffer&& other) noexcept; // Move constructor.
Buffer& operator=(Buffer&& other) noexcept; // Move assignment.
};If a class has no move operations, rvalues fall back to the copy constructor and copy assignment. Standard library types such as std::string#include <string>, std::vector#include <vector> and std::unique_ptr#include <memory> already support moving, and std::unique_ptr#include <memory> can only be moved.
Dan