Copy and Move Semantics
How objects are copied or transferred — and the rule of three/five.
Advanced
- Copy constructor
T(const T&)— makes an independent copy. - Move constructor
T(T&&)— steals the resources of a temporary instead of copying them (much faster for big buffers).
std::vector<int> a(1'000'000);
std::vector<int> b = a; // copy: 1M elements duplicated
std::vector<int> c = std::move(a); // move: c takes a's buffer, a is left empty
Rule of five: if your class manages a resource and defines a destructor, copy constructor/assignment or move constructor/assignment, it probably needs all five. Better still, use standard types (std::vector, std::unique_ptr) and write none (rule of zero).
Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.
Discussion (0)
Sign in or join free to ask questions and discuss this topic.