When should you use unique_ptr, shared_ptr or weak_ptr?
Assesses fundamental understanding of C++ conventions, runtime behavior, and memory/performance considerations.
Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.
Raw new and delete are error-prone, so C++11 introduced smart pointers in <memory> that express ownership.
std::unique_ptr<T>: exclusive ownership, cannot be copied, is movable, and has essentially zero overhead versus a raw pointer. Create withstd::make_unique.std::shared_ptr<T>: shared ownership through an atomic control block with a reference count; the object is destroyed when the last owner goes away. Create withstd::make_shared. Heavier, and the count is thread-safe but the object is not.std::weak_ptr<T>: a non-owning observer of a shared object, used to break cycles.lock()yields ashared_ptror null.
auto a = std::make_unique<Widget>();
auto b = std::make_shared<Widget>();
std::weak_ptr<Widget> w = b;
if (auto s = w.lock()) {
s->use();
}
Prefer unique_ptr by default, upgrade to shared_ptr only for genuine shared ownership, and never create two shared pointers from the same raw pointer, which causes a double free.
Candidate Response Strategy & Interview Tips
- Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
- Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
- Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
- Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.