⚙️ C++ Beginner

What are smart pointers in C++?

Why Interviewers Ask This

Foundational questions like this help interviewers calibrate the rest of the interview. A confident, accurate answer signals that you have solid C++ basics — a prerequisite for any developer role.

Answer

Smart pointers (from <memory>) are RAII wrappers around raw pointers that automatically manage the lifetime of heap-allocated objects — preventing memory leaks and dangling pointers without manual delete. Three types: (1) std::unique_ptr: exclusive ownership — only one unique_ptr can point to an object at a time. Cannot be copied; can be moved. Object is destroyed when the unique_ptr goes out of scope: auto p = std::make_unique<Car>("Toyota", 2022); p->drive(); // Direct use -- no need to delete! // Pass ownership: std::unique_ptr<Car> p2 = std::move(p); // p is now null. Best for: single-owner resources, factory functions, class members; (2) std::shared_ptr: shared ownership — multiple shared_ptrs can point to the same object. Uses reference counting — object destroyed when the last shared_ptr goes away: auto sp1 = std::make_shared<Car>("Honda"); auto sp2 = sp1; // Both own the same Car std::cout << sp1.use_count(); // 2 sp1.reset(); // sp1 releases its share -- count = 1 // Car destroyed when sp2 goes out of scope. Slightly more expensive due to atomic reference count; (3) std::weak_ptr: non-owning observer — doesn't participate in reference counting. Breaks circular references (the main cause of shared_ptr leaks). Lock before use: std::weak_ptr<Car> wp = sp1; if (auto locked = wp.lock()) { locked->drive(); } // Safe to use. Golden rule: prefer make_unique / make_shared over new. Never use raw pointers for ownership.

Common Mistake

Rushing to answer is a common mistake. Take two seconds to structure your response: definition → example → trade-off. This structure makes complex C++ answers easy to follow.