Smart pointers
RAII-owned heap memory that frees itself β no manual delete, no leaks.
std::unique_ptr and std::shared_ptr tie a heap allocation to a scope, so the destructor reclaims it automatically and ownership is explicit in the type.
A smart pointer is an object that owns a heap allocation and frees it in its own destructor. Because the destructor runs deterministically when the pointer goes out of scope, you never call delete by hand and you never leak β this is RAII applied to ownership.
std::unique_ptr<T> models exclusive ownership: exactly one pointer owns the object at a time. It is non-copyable, so the compiler stops you from accidentally creating two owners of the same memory. To hand ownership elsewhere you std::move it. Always create one with std::make_unique<T>(args...) rather than new.
std::shared_ptr<T> models shared ownership via a reference count. Each copy bumps the count; each destruction drops it; the object is freed when the count reaches zero. use_count() reports the current number of owners. Create one with std::make_shared<T>(args...), which allocates the object and its control block in a single allocation.
Choosing between them
Reach for unique_ptr by default β it has zero overhead over a raw pointer and makes ownership obvious. Only use shared_ptr when ownership genuinely needs to be shared across parts of your program that can't agree on a single owner; the reference counting is not free.
Try it 5 examples
unique_ptr owns and frees
C++introfree 7 prints before after scope, proving the Widget destructor fired the moment w left the inner block β RAII reclaims the heap allocation deterministically, with no manual delete.