Smart Pointer Ownership
CONCEPTS:C++ Smart Pointers
Question Variations
- "When should you use `unique_ptr` versus `shared_ptr`?"
- "What problem does `weak_ptr` solve?"
- "Why is `shared_ptr` not a general replacement for ownership design?"
- "How do smart pointers relate to raw non-owning pointers?"
Why This Is Asked
Smart pointers make heap ownership explicit in modern C++. Interviewers use this question to see whether you choose exclusive ownership by default, understand the cost and lifetime model of shared ownership, and prevent reference cycles.
Key Concepts
std::unique_ptrhas one owner and transfers ownership by move.std::shared_ptruses a reference-counted control block for shared ownership.std::weak_ptrobserves ashared_ptr-managed object without keeping it alive.- Prefer
std::make_uniqueandstd::make_sharedfor exception-safe construction.
Question Variations
- “When should you use
unique_ptrversusshared_ptr?” - “What problem does
weak_ptrsolve?” - “Why is
shared_ptrnot a general replacement for ownership design?” - “How do smart pointers relate to raw non-owning pointers?”