Smart Pointers
in C++
Learn how unique_ptr and shared_ptr manage heap memory automatically, preventing leaks and making your code safer and more expressive.
The Memory Problem
In C++, when you allocate memory on the heap with new, you are responsible for releasing it with delete. If you forget, your program leaks memory: the allocated block is never returned to the operating system.
What Are Smart Pointers?
A smart pointer is a C++ object that wraps a raw pointer and automatically deletes the heap memory when the smart pointer goes out of scope. They live in the <memory> header.
Automatic Cleanup in Action
The unique_ptr Rule
A unique_ptr enforces exclusive ownership. Only one unique_ptr may own a given heap object at any time. When that unique_ptr is destroyed, the object is deleted.
The shared_ptr Rule
A shared_ptr uses reference counting. Multiple shared_ptrs can point to the same object. The object is deleted only when the last shared_ptr is destroyed.
unique_ptr vs shared_ptr
| Feature | unique_ptr | shared_ptr |
|---|---|---|
| Ownership | Exclusive (one owner) | Shared (many owners) |
| Copyable? | No | Yes |
| Movable? | Yes | Yes |
| Overhead | Zero extra cost | Reference count + control block |
| Creation | std::make_unique | std::make_shared |
| When to use | Default choice for ownership | When multiple places need the object |
Step-by-Step Usage Guide
Example 1: unique_ptr Basics
Example 2: shared_ptr Counting
Example 3: Smart Pointers with Classes
Why Use make_unique and make_shared?
Passing Smart Pointers to Functions
Ownership Flow Visualized
Common Mistakes
Quick Reference Summary
| Operation | unique_ptr | shared_ptr |
|---|---|---|
| Create | make_unique<T>(args) | make_shared<T>(args) |
| Dereference | *ptr, ptr-> | *ptr, ptr-> |
| Transfer | std::move(ptr) | Copy or move |
| Check null | if (ptr) | if (ptr) |
| Get raw | ptr.get() | ptr.get() |
| Count owners | N/A (always 1) | ptr.use_count() |
| Reset | ptr.reset() | ptr.reset() |
Question 1 of 5
What is the primary advantage of using smart pointers over raw pointers in C++?
Question 2 of 5
Which line of code will cause a compile error?
Question 3 of 5
A shared_ptr is copied 3 times. What is the reference count after all copies are made?
Question 4 of 5
After calling std::move(ptr) on a unique_ptr, what is the value of ptr?
Question 5 of 5
Which function should you prefer for creating a unique_ptr?