Copy & Move Semantics (Rule of Three/Five) in C++
Copying duplicates resources; moving steals them, leaving the source valid-but-empty. The compiler-generated copy just copies members (disastrous for owning raw pointers β double-free), so resource-owning classes define the Rule of Five: destructor, copy constructor, copy assignment, move constructor, move assignment β or the Rule of Zero by composing vector/string/unique_ptr that already do.
Moves fire automatically on temporaries and std::move-marked values, making return-by-value and vector growth cheap. A moved-from object must remain destructible and assignable β the only guarantees the library demands.
Default copy is shallow
Member-wise copying duplicates a raw pointer, not its target β two owners, one delete each, heap corruption.
Rule of Five
Owning classes define destructor + copy/move constructor + copy/move assignment together β declaring any one should prompt reviewing all five.
Moves steal cheaply
A move constructor copies the pointer then nulls the source β O(1) ownership transfer, no allocation, source left empty but valid.
Prefer Rule of Zero
Members like std::vector and std::unique_ptr already implement the Five correctly β compose them and write none of it yourself.
#include <iostream>#include <utility>#include <vector>Β int main() { std::vector<int> a{1, 2, 3}; std::vector<int> b = a; std::vector<int> c = std::move(a); std::cout << b.size() << ", " << c.size() << ", " << a.size() << std::endl; return 0;}Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself β building beats watching.