Smart Pointers in C++
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.
unique_ptr: sole owner
auto p = std::make_unique<Widget>(); — exactly one owner, movable but never copyable, freed automatically. Default to this.
shared_ptr: shared ownership
Copies share one object with a count; destruction happens when the last owner dies — for genuinely shared lifetimes only.
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.
make_* over new
make_unique/make_shared bundle allocation with construction — exception-safe, single-expression, and (for shared) one allocation instead of two.
#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;}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.