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.
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.
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