What it's for
- Every C++ program that allocates: smart pointers tie a heap block's life to its owner's life, so the free happens even when the code path surprises you.
- They are the default answer to "who deletes this?" — the question raw new/delete leaves to you.
Good to know
unique_ptr costs nothing extra — same size, same speed as a raw pointer. shared_ptr keeps a small count next to the block and updates it atomically; that bookkeeping is its price.
How it works, step by step
Why each step follows
- A raw pointer is just an address — the compiler never promised to call delete, so an early return leaks and a premature delete dangles.
- unique_ptr owns exclusively, so its destructor knows the block is unshared and can free it on the spot; that is also why copies are banned and only moves compile.
- shared_ptr's count makes "last one out frees it" mechanical: each copy adds one, each goodbye drops one, zero means gone.
- A cycle of shared pointers keeps every count at one forever. weak_ptr watches without counting, so the count can reach zero and the ring collapses.
Before you rely on it
This is a model of ownership, not of your compiler: real destructors, RAII timing and shared_ptr's control block are simplified away. The leak, the dangle, the automatic free and the cycle are exactly as shown.