What are Smart Pointers in C++?
Learn C++ smart pointers — unique_ptr, shared_ptr and weak_ptr — how RAII and reference counting prevent leaks, with clear examples and interview tips.
Expected Interview Answer
Smart pointers are class templates in the C++ standard library that own and manage a heap-allocated object, automatically freeing it when the pointer goes out of scope, which prevents memory leaks and dangling pointers.
The three main types are std::unique_ptr for exclusive ownership, std::shared_ptr for shared reference-counted ownership, and std::weak_ptr for a non-owning observer that breaks reference cycles. They apply the RAII idiom: the resource's lifetime is tied to an object's scope, so destruction runs deterministically. Prefer std::make_unique and std::make_shared to construct them safely and efficiently.
- Automatic deallocation prevents memory leaks
- Deterministic, exception-safe cleanup via RAII
- Clear ownership semantics in the type system
- unique_ptr has zero runtime overhead over a raw pointer
- weak_ptr breaks reference cycles that leak with shared_ptr
AI Mentor Explanation
Think of the ground staff who own the match ball for a session. A unique_ptr is like handing one specific ball to exactly one bowler at a time; when the over ends the ball is passed on, never duplicated. A shared_ptr is like a practice ball tracked by a counter on the whiteboard, wiped from the bag only after the last player who signed for it returns it.
Step-by-Step Explanation
Step 1
Understand the leak problem
Raw new without a matching delete, or an exception thrown before delete, leaks the allocated memory.
Step 2
Choose unique_ptr for sole ownership
Use std::make_unique<T>() when exactly one owner should control the object's lifetime.
Step 3
Choose shared_ptr for shared ownership
Use std::make_shared<T>() when multiple owners share the object; a reference count tracks them.
Step 4
Break cycles with weak_ptr
When two shared_ptrs reference each other, make one a weak_ptr so the count can reach zero.
Step 5
Let scope do the cleanup
When the smart pointer goes out of scope its destructor frees the object automatically.
What Interviewer Expects
- Names unique_ptr, shared_ptr and weak_ptr and their ownership models
- Understands RAII and deterministic destruction
- Knows make_unique and make_shared are preferred
- Can explain reference counting and cyclic-reference leaks
- Knows unique_ptr is move-only and has no overhead
Common Mistakes
- Using shared_ptr everywhere when unique_ptr suffices
- Creating reference cycles with two shared_ptrs and leaking
- Calling delete manually on a smart-pointer-managed object
- Copying a unique_ptr instead of std::move-ing it
- Constructing from a raw pointer twice, causing a double free
Best Answer (HR Friendly)
“Smart pointers are helpers in C++ that take care of freeing memory for you automatically, so you don't forget and cause a leak. There are a few kinds depending on whether one part of the program or several parts share ownership of the same data.”
Code Example
#include <memory>
#include <iostream>
struct Widget {
Widget() { std::cout << "built\n"; }
~Widget() { std::cout << "freed\n"; }
void use() { std::cout << "using widget\n"; }
};
int main() {
// Exclusive ownership; freed at end of scope.
std::unique_ptr<Widget> u = std::make_unique<Widget>();
u->use();
// Shared ownership tracked by a reference count.
std::shared_ptr<Widget> a = std::make_shared<Widget>();
std::shared_ptr<Widget> b = a; // count == 2
std::cout << "count: " << a.use_count() << "\n";
// Non-owning observer that does not raise the count.
std::weak_ptr<Widget> w = a;
if (auto locked = w.lock()) locked->use(); // safe access
return 0; // u, a, b destroyed here; Widget freed exactly once each
}Follow-up Questions
- What is the difference between unique_ptr and shared_ptr?
- Why prefer make_shared over new with shared_ptr?
- How does weak_ptr break a reference cycle?
- What is RAII and how do smart pointers implement it?
- Can you use a custom deleter with a smart pointer?
MCQ Practice
1. Which smart pointer models exclusive, non-copyable ownership?
std::unique_ptr owns its object exclusively and is move-only; it cannot be copied.
2. What problem does std::weak_ptr primarily solve?
weak_ptr observes a shared_ptr without incrementing the count, letting cyclic references reach zero and free.
3. Why is std::make_shared usually preferred over shared_ptr(new T)?
make_shared allocates the object and its control block together, which is more efficient and exception-safe.
Flash Cards
unique_ptr ownership model? — Exclusive, move-only ownership with zero overhead over a raw pointer.
shared_ptr ownership model? — Shared ownership via an atomic reference count; frees when the count hits zero.
What is weak_ptr for? — A non-owning observer used to break reference cycles; access via lock().
Which idiom do smart pointers implement? — RAII — resource lifetime is tied to object scope for deterministic cleanup.
Preferred way to build them? — std::make_unique and std::make_shared.