C++ Medium technical 1 views 1 min read

When should you use unique_ptr, shared_ptr or weak_ptr?

Peer-reviewed by HireXTech Technical Panel Updated for 2025/2026 hiring Editorial standards
Practise this track
Interviewer Expectations for this Question
01
Core Competency

Assesses fundamental understanding of C++ conventions, runtime behavior, and memory/performance considerations.

02
Evaluation Criteria

Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.

Comprehensive Model Answer Verified Solution

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 with std::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 with std::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 a shared_ptr or 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

  1. Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
  2. Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
  3. Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
  4. Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.
Related Topics & Skills
Spotted an error or have an alternative solution?