Learn C++
#include "advanced/smart_pointers.hpp"

Smart Pointers in C++

//concept

Smart pointers automate ownership: unique_ptr owns exclusively (move-only, zero overhead — the default choice), shared_ptr shares via reference counting (last owner destroys), and weak_ptr observes shared ownership without extending it (breaking cycles). All delete automatically, all forbid the classic leak/double-free pair.

Prefer make_unique/make_shared over raw new — single allocation, exception-safe, no naked new in sight. Raw pointers remain for non-owning observation; owning raw new/delete is legacy code smell.

//how it works
1

unique_ptr: sole owner

auto p = std::make_unique<Widget>(); — exactly one owner, movable but never copyable, freed automatically. Default to this.

2

shared_ptr: shared ownership

Copies share one object with a count; destruction happens when the last owner dies — for genuinely shared lifetimes only.

3

weak_ptr: non-owning peek

Observes a shared_ptr without keeping it alive; lock() yields a temporary shared_ptr or empty when expired — the cycle-breaker.

4

make_* over new

make_unique/make_shared bundle allocation with construction — exception-safe, single-expression, and (for shared) one allocation instead of two.

//example
#include <iostream>
#include <memory>
#include <string>
 
int main() {
auto owner = std::make_unique<std::string>("cargo");
std::cout << *owner << ", " << owner->size() << std::endl;
return 0;
}
Output
cargo, 5
1make_unique allocates the string and wraps it — owner is the sole owner from birth.
2*owner and owner-> reach the object with raw-pointer syntax and zero overhead.
3At scope exit owner destroys and frees automatically — no delete written, none needed, none leaked.
//use cases
Owning heap objects with unique_ptr as the zero-cost default
Shared caches and graphs with shared_ptr plus weak_ptr back-links
Factory functions returning unique_ptr (transfer) or shared_ptr (shared)
Erasing naked new/delete from modern codebases entirely

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.