Smart pointers wrap raw pointers with RAII ownership—automatically calling delete when the last owner goes away. Prefer them over scattered new/delete.
std::unique_ptr
auto p = std::make_unique<int>(42);
// delete called when p goes out of scope
unique_ptr has exclusive ownership—it is move-only, not copyable.
std::shared_ptr (preview)
shared_ptr uses reference counting when multiple owners must share one object. Default to unique_ptr; reach for shared_ptr when sharing is required.
Important interview questions and answers
- Q: make_unique benefits?
A: Exception-safe, concise, avoids writingnewdirectly. - Q: unique_ptr vs shared_ptr?
A: Exclusive vs shared ownership; shared_ptr has atomic refcount overhead.
Self-check
- Can you copy a unique_ptr?
- When is delete called for unique_ptr?
Tip: Default to std::unique_ptr for exclusive ownership—like Rust move ownership, but enforced by convention and move-only types.
Interview prep
- unique_ptr vs shared_ptr?
unique_ptrhas exclusive ownership;shared_ptruses reference counting for shared ownership.- make_unique benefits?
Exception-safe creation without writing
newdirectly in user code.