Interview Q&A · C++ · 10 questions in this topic
RAII & Smart Pointers — C++ Interview Q&A
Deterministic resource management — RAII, unique/shared/weak pointers, cycles, and custom deleters. Part of Pointers, References & RAII · 213 questions in the C++ bank.
What is RAII and why is it the central C++ idiom?
Answer
RAII (Resource Acquisition Is Initialization) ties resource lifetime to object lifetime: the constructor acquires, the destructor releases. Because destructors run deterministically at scope exit — including during exception unwinding — resources (memory, files, locks, handles) are freed exactly once on every path.
std::string, containers, lock_guard and smart pointers are all RAII types; writing new RAII wrappers is how you make manual cleanup unnecessary.
Example
#include <mutex> void work(std::mutex& m) { std::lock_guard<std::mutex> g(m); // acquire // ... exceptions safe: g destructor unlocks on every path }
💡 Tie RAII to exceptions explicitly — stack unwinding running destructors is why RAII beats finally-style cleanup.
When do you use `unique_ptr`, `shared_ptr` and `weak_ptr`?
Answer
unique_ptr is exclusive ownership with zero overhead — the default smart pointer. shared_ptr is shared ownership via atomic reference counting — use only when truly shared. weak_ptr is a non-owning observer of shared_ptr that lock()s to a temporary shared_ptr, breaking cycles and expressing caches/observers.
Default to unique_ptr; reach for shared_ptr only with proven shared lifetime, and weak_ptr for back-references and caches.
Key points
- 1unique_ptr — exclusive, movable, zero cost; factory: make_unique.
- 2shared_ptr — counted, thread-safe count, cyclic danger; factory: make_shared.
- 3weak_ptr — observes shared_ptr, lock() to use, breaks cycles.
Example
#include <memory> auto u = std::make_unique<int>(5); // exclusive std::shared_ptr<int> s = std::make_shared<int>(6); std::weak_ptr<int> w = s; // observes, owns nothing if (auto tmp = w.lock()) { /* safe to use */ }
💡 Default-unique, shared-only-when-proven, weak-for-cycles is the ownership mantra.
How does `shared_ptr` reference counting work? What does it cost?
Answer
shared_ptr points at the object plus a control block holding strong and weak counts. Copying increments (atomically) the strong count; destruction decrements; at zero the object is destroyed, and at zero weak count the block itself is freed. make_shared fuses object and block into one allocation.
Costs: one extra allocation (without make_shared), atomic count traffic on every copy (visible in hot loops), and 16 bytes per shared_ptr (two pointers). Cycles need weak_ptr to break.
Example
auto s1 = std::make_shared<int>(1); // one allocation { auto s2 = s1; // strong count 2 (atomic inc) } // s2 dies: count back to 1
What is a `shared_ptr` cycle and how does `weak_ptr` break it?
Answer
A cycle (A owns shared_ptr to B, B owns shared_ptr to A) keeps both strong counts above zero forever — a leak no reference count can collect. Replacing one direction (the back-pointer, parent link, observer or cache) with weak_ptr removes that edge from ownership: the weak side observes without keeping the target alive.
Child-to-parent links are the canonical weak_ptr direction.
Example
struct Node : std::enable_shared_from_this<Node> { std::shared_ptr<Node> child; // owning: parent -> child std::weak_ptr<Node> parent; // non-owning: child -> parent };
Why should you use `make_unique` / `make_shared` instead of `new`?
Answer
They prevent leaks in argument evaluation (f(unique_ptr(new A), unique_ptr(new B)) could leak if evaluation interleaves with a throw — fixed argument order only since C++17, and style still matters), perform one allocation for shared_ptr (object plus control block fused), forward constructor arguments perfectly, and keep raw new out of user code.
Exception: when you need a custom deleter or a non-public constructor, construct the smart pointer directly.
Example
auto u = std::make_unique<Widget>(1, "x"); // no raw new // f(std::unique_ptr<A>(new A), g()); // risky pre-C++17 ordering // f(std::make_unique<A>(), g()); // safe
💡 One allocation plus exception safety is the two-part answer.
What is move semantics and what makes a type movable?
Answer
Move semantics transfer resources from an expiring source instead of copying: the move constructor/assignment pilfer the source's buffer and leave it in a valid-but-unspecified state. A type is movable when it defines (or gets implicitly) move operations — typically by owning a stealable handle like a pointer.
Moves enable cheap vector growth, factory returns without copies, and unique_ptr transfer. Moved-from objects must remain destructible and assignable.
Example
std::string a = "hello"; std::string b = std::move(a); // a pilfered, valid-but-unspecified // use b; do not assume anything about a except it can be destroyed/assigned
What is the difference between shallow copy and deep copy?
Answer
Shallow copy duplicates the handle (pointer copied, pointee shared) — the default memberwise copy. Deep copy duplicates the pointee too — independent lifetimes at the price of allocation. Sharing after a shallow copy causes double-free or action-at-a-distance; deep copy costs but isolates.
C++ forces the choice explicitly in copy constructors/assignments; smart-pointer members (unique = move-only, shared = shared-own) encode the answer in the type.
Example
struct Shallow { int* p; }; // default copy shares *p struct Deep { int* p = nullptr; Deep(const Deep& o) : p(o.p ? new int(*o.p) : nullptr) {} ~Deep() { delete p; } };
What is a custom deleter and when do you need one?
Answer
A custom deleter replaces default delete for non-new resources: fclose for FILE*, close for fds, library free functions, or array forms. unique_ptr takes the deleter as part of its type (zero overhead with stateless lambdas); shared_ptr type-erases it.
Deleters turn any C handle into a RAII owner with a single declaration.
Example
#include <cstdio> struct FClose { void operator()(std::FILE* f) const { if (f) std::fclose(f); } }; std::unique_ptr<std::FILE, FClose> f(std::fopen("a.txt", "r"));
What is `enable_shared_from_this` and what is the classic mistake with it?
Answer
It lets an object already owned by shared_ptr safely mint additional shared_ptrs to itself via shared_from_this(), sharing one control block. The classic mistake is calling shared_from_this() on an object not yet owned by shared_ptr (e.g. in its constructor or on a stack instance) — that throws std::bad_weak_ptr. Also, never build two shared_ptr families from the same raw this (double ownership, double free).
Construct through make_shared and only call shared_from_this after ownership exists.
Example
struct S : std::enable_shared_from_this<S> { std::shared_ptr<S> self() { return shared_from_this(); } }; auto s = std::make_shared<S>(); auto s2 = s->self(); // shares ownership, one control block
Who owns memory in a good C++ design? (Ownership thinking.)
Answer
Every allocation has exactly one owner whose lifetime governs it: values own themselves on the stack, containers own elements, unique_ptr owns exclusive heap objects, shared_ptr co-owns genuinely shared ones. Non-owners use references, views, spans or weak_ptr — never owning raw pointers.
If you cannot name the owner of a pointer, the design is already broken; encode ownership in types so the compiler enforces it.
Key points
- 1Exclusive — unique_ptr, values, members.
- 2Shared — shared_ptr only when lifetime is genuinely shared.
- 3Non-owning — T&, string_view, span, raw pointer as observer, weak_ptr.
💡 Answer ownership questions by naming the owner type — that habit is what interviewers are really testing.
Recommended resourcesAffiliate links · may earn us a commission