What is a smart pointer in C++?
A smart pointer is a class that wraps a raw pointer and automatically frees the memory when it is no longer needed, so you do not call delete yourself. The main types are unique_ptr for single ownership, shared_ptr for shared ownership with reference counting, and weak_ptr to break reference cycles. They follow the idea that a resource is tied to an object's lifetime.
- A smart pointer wraps a raw pointer and frees the memory automatically when it goes out of scope.
- unique_ptr is single ownership, shared_ptr is shared with reference counting, and weak_ptr breaks cycles.
- Smart pointers apply RAII to memory, which prevents most leaks and double frees.
Why they exist
Manual new and delete is error prone. Forget a delete and you leak memory, delete twice and you crash. Smart pointers free the memory automatically when they go out of scope, which prevents most of these bugs.
#include <memory>
std::unique_ptr<int> p = std::make_unique<int>(5);
// no delete needed, freed automatically when p goes out of scope
The three types
- unique_ptr: one owner, cannot be copied, very light.
- shared_ptr: many owners, freed when the last one is gone.
- weak_ptr: observes a shared_ptr without owning it, avoids cycles.
This ties to RAII, resource acquisition is initialisation. Saying smart pointers apply RAII to memory, so cleanup happens automatically at end of scope, is exactly the phrasing senior interviewers reward.
Frequently asked questions
What is the difference between unique_ptr and shared_ptr?
unique_ptr allows exactly one owner and cannot be copied, while shared_ptr allows many owners and frees the memory when the last one is destroyed.
What problem does weak_ptr solve?
It observes a shared_ptr without adding to the reference count, which breaks reference cycles that would otherwise stop memory from ever being freed.
Common follow up questions
Related interview questions
Want the full C++ guide?
Read every C++ concept with notes, diagrams, and code in one place. Track your progress as you go.
Open the C++ guide All C++ questions