Interview Question

unique_ptr vs shared_ptr?

unique_ptr owns exclusively; shared_ptr shares ownership.

💡 Concept ✅ Quick Revision 🧠 C++

Answer

std::unique_ptr represents exclusive ownership, while std::shared_ptr uses shared ownership through reference counting. • unique_ptr is movable but not copyable. • shared_ptr copies share a control block and destroy the object when the last owning reference is released. • Prefer unique_ptr unless the design truly requires shared ownership.

💡 C++ Example

auto exclusive = std::make_unique<int>(42); auto shared_a = std::make_shared<int>(7); auto shared_b = shared_a;

⚡ Quick Revision

unique_ptr owns exclusively; shared_ptr shares ownership.