Learn C++
#include "oopadvanced/copy_move.hpp"

Copy & Move Semantics (Rule of Three/Five) in C++

//concept

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.

//how it works
1

Default copy is shallow

Member-wise copying duplicates a raw pointer, not its target β€” two owners, one delete each, heap corruption.

2

Rule of Five

Owning classes define destructor + copy/move constructor + copy/move assignment together β€” declaring any one should prompt reviewing all five.

3

Moves steal cheaply

A move constructor copies the pointer then nulls the source β€” O(1) ownership transfer, no allocation, source left empty but valid.

4

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.

//example
#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;
}
Output
3, 3, 0
1b = a copies β€” b owns its own duplicate three elements while a keeps its own.
2c = std::move(a) steals a's storage instead of copying; a is left valid but empty.
33, 3, 0 prints β€” copy duplicated, move transferred, source emptied but still destructible.
//use cases
Owning classes (buffers, handles) that must define or delete all five specials
Returning heavy objects by value, trusting moves to keep it free
Moving elements during vector reallocation instead of copying them
Deleting copy (Widget(const Widget&) = delete;) for uncopyable resources like locks

Recommended resourcesAffiliate links Β· may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice β€” pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from β€” great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself β€” building beats watching.