Smart Pointers
Automatic, exception-safe ownership for heap objects
Big Idea: A smart pointer is a small stack object that owns a heap allocation and frees it automatically the moment ownership ends. Instead of pairing every
new with a matching delete by hand, you let the pointer's destructor do it for you. This is RAII (Resource Acquisition Is Initialization) applied to memory: the lifetime of a resource is tied to the lifetime of an object on the stack.
By the end you will be able to:
- explain why raw
new/deleteis fragile, - use
std::unique_ptrfor exclusive ownership and move it around, - use
std::shared_ptrfor shared ownership and read its reference count, - use
std::weak_ptrto observe without owning and to break reference cycles.
1. The problem with raw new / delete
You already know how to allocate on the heap with new and release with delete. The trouble is that you become responsible for the delete, and there are many ways to get it wrong:
- Leak: you forget the
delete, or an earlyreturnskips it, and the memory is never returned. - Dangling pointer: you
deleteand keep using the pointer. - Double free: two code paths both
deletethe same object. - Exception leak: an exception is thrown between
newanddelete, so thedeletenever runs.
void process() {
Widget* w = new Widget(); // manual allocation
if (!w->load())
return; // BUG: leaks w, delete never runs
w->run();
delete w; // easy to forget, or skip via exception
}
Smart pointers remove this whole class of bugs by making the compiler and the destructor responsible for cleanup. Because a smart pointer is a stack object, its destructor runs automatically at the end of the scope, on every path, including when an exception unwinds the stack.