C++ Smart Pointer Interview Questions (unique_ptr, shared_ptr, weak_ptr)
Senior interviews on smart pointers go well beyond "what is unique_ptr?". Interviewers want to see that you understand ownership design, control-block mechanics, thread safety, performance costs, and the classic bugs. This set of 22 questions progresses from fundamentals to implementation-level topics, each with an interview-ready answer, explanation, and example.
Fundamentals
1. What problem do smart pointers solve, and how do the three types differ?
Smart pointers encode ownership in the type system and use RAII to release the resource automatically, including when exceptions are thrown. They largely eliminate manual delete, leaks, and double-frees.
| Type | Ownership | Copyable? | Typical cost |
|---|---|---|---|
unique_ptr |
Exclusive (one owner) | No (move only) | Same as a raw pointer (with the default deleter) |
shared_ptr |
Shared (reference counted) | Yes | Control block + atomic reference counting |
weak_ptr |
None (non-owning observer of a shared_ptr) |
Yes | Pointer to the control block; lock() costs a CAS |
auto u = std::make_unique<Widget>(); // sole owner
auto s = std::make_shared<Widget>(); // shared owner
std::weak_ptr<Widget> w = s; // observes s, doesn't keep Widget alive
Interview takeaway: The choice of smart pointer is a statement about who owns the object and for how long. Default to
unique_ptr; reach forshared_ptronly when ownership is genuinely shared.
2. What are the semantics and cost of std::unique_ptr?
unique_ptr has exclusive ownership. It is move-only: copying is deleted, and moving transfers ownership and leaves the source null.
std::unique_ptr<int> a = std::make_unique<int>(42);
// auto b = a; // error: copy deleted
auto b = std::move(a); // OK: a is now nullptr
Cost:
- With the default deleter,
sizeof(unique_ptr<T>) == sizeof(T*)and there is no runtime overhead compared with a raw pointer. The deleter is stored using the empty-base/[[no_unique_address]]optimization. - A stateless deleter (an empty functor or captureless lambda) keeps that size. A function-pointer deleter or stateful deleter adds to the size.
- The deleter is part of the type:
unique_ptr<T, D1>andunique_ptr<T, D2>are different types.
Useful members:
p.get(); // raw pointer, ownership unchanged
p.release(); // gives up ownership WITHOUT deleting, returns the raw pointer
p.reset(); // deletes the current object
p.reset(q); // deletes current, takes ownership of q
p.swap(other);
Interview takeaway:
unique_ptris a zero-cost abstraction, andrelease()does not delete. Confusingrelease()andreset()is a classic leak.
3. How does std::shared_ptr work internally?
A shared_ptr holds two pointers: one to the managed object and one to a heap-allocated control block.
The control block contains:
- A strong count (number of
shared_ptrs owning the object) - A weak count (number of
weak_ptrs, plus 1 held collectively by all strong owners) - The deleter and allocator (type-erased)
- With
make_shared, the object itself
shared_ptr A ──┐
shared_ptr B ──┼──► [ Control Block: strong=3, weak=2, deleter ]
shared_ptr C ──┘ │
└──► Object (separate allocation, unless make_shared)
weak_ptr W ─────► Control Block
Lifecycle:
- When the strong count hits 0, the object is destroyed (via the deleter).
- When the weak count hits 0, the control block itself is freed.
Reference count updates are atomic, so copying a shared_ptr is thread-safe with respect to the counts (see Q14). That is also where the cost comes from.
Interview takeaway:
sizeof(shared_ptr<T>)is two pointers. The object is destroyed when the strong count reaches zero, but the control block lives until the weak count reaches zero.
4. What is weak_ptr, and when do you use it?
A weak_ptr is a non-owning observer of an object managed by a shared_ptr. It doesn't increase the strong count, so it doesn't keep the object alive. Use it to:
- Break reference cycles (Q7)
- Build caches and observer lists that shouldn't extend lifetimes
- Hold a "maybe still alive" back-reference (for example, a child pointing at its parent)
You can't dereference a weak_ptr directly. You must first lock() it, which atomically returns a shared_ptr (empty if the object is gone):
std::weak_ptr<Widget> weak = shared;
if (auto strong = weak.lock()) { // atomic "is it alive? if so, keep it alive"
strong->doWork(); // safe: object can't die while `strong` exists
} else {
// object has been destroyed
}
Interview takeaway: Always use the
lock()pattern.expired()followed bylock()is a race (see Q17).
5. Why prefer make_unique / make_shared over new?
auto a = std::make_unique<Widget>(1, 2);
auto b = std::make_shared<Widget>(1, 2);
std::shared_ptr<Widget> c(new Widget(1, 2)); // works, but usually worse
Reasons:
- Less repetition: the type is named once.
- Exception safety (pre-C++17):
f(std::shared_ptr<T>(new T), g())could leak ifg()threw between thenewand theshared_ptrconstruction. C++17's stricter argument sequencing closes that hole, butmake_*is still the clearer habit. make_shareddoes one allocation: the object and control block are allocated together, which is faster and more cache-friendly than the two allocations ofshared_ptr<T>(new T).
Caveats of make_shared
- Because the object and control block share one allocation, the memory isn't freed until the weak count also reaches zero. The object is destroyed on time, but a long-lived
weak_ptrkeeps the whole block (including the now-dead object's storage) allocated. For large objects with long-lived weak references, this matters. - You can't pass a custom deleter (use
allocate_sharedfor a custom allocator, or theshared_ptrconstructor for a deleter). - It needs an accessible constructor, so a private constructor requires a workaround (a passkey idiom or a private helper).
- It ignores class-specific
operator new/operator delete.
Interview takeaway: Prefer
make_*, and know themake_shared+ long-livedweak_ptrmemory-retention trade-off.
6. How should you pass and return smart pointers?
This follows the C++ Core Guidelines (R.30 to R.37): the parameter type should state the lifetime contract.
| Function intent | Parameter type | Meaning |
|---|---|---|
| Just use the object (most common) | T& or T* |
Not involved in ownership at all |
| Take ownership (a "sink") | std::unique_ptr<T> by value |
Caller must std::move in |
| Share ownership (store a copy) | std::shared_ptr<T> by value |
Caller keeps its own, function gets another |
| Possibly reseat the caller's smart pointer | std::unique_ptr<T>& / std::shared_ptr<T>& |
Function may assign a new object |
| Might retain a reference count | const std::shared_ptr<T>& |
Rare. Use only if it conditionally copies |
void render(const Widget& w); // just uses it
void adopt(std::unique_ptr<Widget> w); // takes ownership
void keep(std::shared_ptr<Widget> w); // shares ownership
Returning:
std::unique_ptr<Widget> makeWidget() {
auto w = std::make_unique<Widget>();
return w; // implicit move; don't write std::move(w)
}
Factories should return unique_ptr, because it converts to shared_ptr for free but not the other way around (Q13).
Interview takeaway: Don't pass a smart pointer just to use the object. Pass a reference. Taking a
shared_ptrby value on every call is both a design smell and a performance cost (Q15).
Intermediate
7. What is a reference cycle, and how do you break it?
If two objects hold shared_ptrs to each other, their strong counts never reach zero and both leak.
struct Child;
struct Parent {
std::shared_ptr<Child> child;
};
struct Child {
std::shared_ptr<Parent> parent; // BUG: cycle, neither is ever destroyed
};
Fix: the owning direction uses shared_ptr and the back-reference uses weak_ptr.
struct Child {
std::weak_ptr<Parent> parent; // non-owning back-reference
};
// Usage
if (auto p = child.parent.lock()) {
p->notify();
}
Typical cycle sources: parent/child trees, doubly linked lists, observer registrations, and callbacks stored by the object they capture (Q18).
Interview takeaway: Ownership should form a DAG. Back-references, caches and observers are
weak_ptr(or raw/non-owning pointers when the lifetime is guaranteed).
8. What is enable_shared_from_this, and what are its pitfalls?
If a member function needs a shared_ptr to this, you can't just write std::shared_ptr<T>(this), because that creates a second, independent control block and leads to a double delete. Inherit from std::enable_shared_from_this<T> instead:
class Session : public std::enable_shared_from_this<Session> {
public:
std::shared_ptr<Session> getPtr() { return shared_from_this(); }
std::weak_ptr<Session> getWeak() { return weak_from_this(); } // C++17
};
auto s = std::make_shared<Session>();
auto s2 = s->getPtr(); // shares s's control block
Pitfalls:
shared_from_this()requires the object to already be owned by ashared_ptr. Otherwise it throwsstd::bad_weak_ptr(C++17 guarantees this; earlier it was undefined).- You can't call it in the constructor, because no
shared_ptrowns the object yet. Use a factory function that constructs and then returns ashared_ptr. - Inherit publicly and only for classes always managed by
shared_ptr. - It adds a
weak_ptrmember to the object.
Session stackObj;
// stackObj.shared_from_this(); // throws std::bad_weak_ptr
Interview takeaway: Never construct a second
shared_ptrfrom a raw pointer that is already owned.enable_shared_from_thisis the sanctioned way to get one fromthis.
9. How do custom deleters work, and how do they differ between unique_ptr and shared_ptr?
A deleter customizes how the resource is released, which is how you manage non-memory resources (files, sockets, handles) or memory from other allocators.
// unique_ptr: the deleter is part of the TYPE
struct FileCloser {
void operator()(FILE* f) const { if (f) std::fclose(f); }
};
std::unique_ptr<FILE, FileCloser> file(std::fopen("data.txt", "r"));
// Captureless lambda (C++20: default-constructible)
auto closer = [](FILE* f) { std::fclose(f); };
std::unique_ptr<FILE, decltype(closer)> f2(std::fopen("x", "r"), closer);
// shared_ptr: the deleter is passed to the constructor and type-ERASED
std::shared_ptr<FILE> f3(std::fopen("x", "r"), [](FILE* f) { std::fclose(f); });
| Aspect | unique_ptr |
shared_ptr |
|---|---|---|
| Deleter in the type? | Yes (a template parameter) | No (type-erased, stored in the control block) |
Effect on sizeof |
Stateful deleters increase it | None (the deleter lives in the control block) |
| Runtime cost | Zero for stateless deleters | Indirect call through the control block |
| Flexibility | Different deleter = different type | Different deleters, same shared_ptr<T> type |
Interview takeaway:
unique_ptrputs the deleter in the type (zero overhead, less flexible).shared_ptrtype-erases it (flexible, small cost). That difference also explains Q10.
10. Why does shared_ptr<Base> work without a virtual destructor but unique_ptr<Base> does not?
The shared_ptr constructor captures the deleter for the concrete type at the point where the pointer is first created, and stores it type-erased in the control block. So the right destructor runs even if you later convert to shared_ptr<Base>:
struct Base { ~Base() { std::cout << "~Base\n"; } }; // NOT virtual
struct Derived : Base { ~Derived() { std::cout << "~Derived\n"; } };
std::shared_ptr<Base> s = std::make_shared<Derived>(); // OK: ~Derived, then ~Base
unique_ptr<Base> uses std::default_delete<Base>, which calls delete on a Base*. Without a virtual destructor, that is undefined behavior:
std::unique_ptr<Base> u = std::make_unique<Derived>(); // UB: deletes via Base*
Even so, give polymorphic base classes a virtual destructor. Relying on shared_ptr's behavior is fragile (it breaks as soon as someone holds the object through a raw pointer or a unique_ptr).
Interview takeaway:
shared_ptrremembers the original type's deleter;unique_ptrdoesn't. Both are reasons to just write a virtual destructor.
11. What is the shared_ptr aliasing constructor?
It creates a shared_ptr that shares ownership with one object but points to something else, typically a member or sub-object.
struct Engine { int hp; };
struct Car { Engine engine; };
auto car = std::make_shared<Car>();
std::shared_ptr<Engine> engine(car, &car->engine); // owns Car, points to its Engine
car.reset();
// The Car is still alive because `engine` shares ownership of it.
engine->hp = 300; // safe
Rules of thumb:
- The returned pointer's
get()is the second argument, but the reference counts belong to the first. use_count()is shared betweencarandengine.- It is useful for handing out a pointer to a member or an array element while keeping the whole parent alive, with no extra allocation.
Interview takeaway: The aliasing constructor separates "what keeps me alive" from "what I point at".
12. How do you use unique_ptr with an incomplete type (pimpl)?
unique_ptr<Impl> is the standard pimpl holder, but default_delete<Impl> requires Impl to be complete wherever the deleter is instantiated (the destructor, move assignment and reset). If you leave the special members defaulted in the header, the compiler tries to instantiate them where Impl is still incomplete and fails.
// widget.h
class Widget {
public:
Widget();
~Widget(); // declared here...
Widget(Widget&&) noexcept;
Widget& operator=(Widget&&) noexcept;
private:
struct Impl; // incomplete here
std::unique_ptr<Impl> pimpl_;
};
// widget.cpp
struct Widget::Impl { /* ... */ };
Widget::Widget() : pimpl_(std::make_unique<Impl>()) {}
Widget::~Widget() = default; // ...defined where Impl is complete
Widget::Widget(Widget&&) noexcept = default;
Widget& Widget::operator=(Widget&&) noexcept = default;
shared_ptr<Impl> has no such restriction, because its deleter was captured at construction (when the type was complete), but it gives shared (copyable) semantics you probably don't want for a pimpl.
Interview takeaway: With
unique_ptrpimpl, declare the special members in the header and define them in the .cpp where the type is complete.
13. How do conversions between smart pointers work (and arrays)?
unique_ptr→shared_ptr: allowed, by move. A function that returnsunique_ptrcan be used to initialize ashared_ptrdirectly.std::shared_ptr<Widget> s = makeWidget(); // returns unique_ptr<Widget> std::unique_ptr<Widget> u = std::make_unique<Widget>(); std::shared_ptr<Widget> s2 = std::move(u); // u is now nullshared_ptr→unique_ptr: not possible, because other owners may exist. (You can't safely take exclusive ownership back.)- Derived → Base: both types convert (
unique_ptr<Derived>tounique_ptr<Base>, same forshared_ptr), andshared_ptralso supportsstatic_pointer_cast,dynamic_pointer_cast,const_pointer_castandreinterpret_pointer_cast. - Arrays:
Astd::unique_ptr<int[]> a = std::make_unique<int[]>(10); // value-initialized, delete[] a[3] = 7; std::shared_ptr<int[]> b = std::make_shared<int[]>(10); // C++20 (shared_ptr<T[]> since C++17)unique_ptr<Derived[]>does not convert tounique_ptr<Base[]>. Mixingnew[]with a non-array smart pointer (or the reverse) is undefined behavior.
Interview takeaway: Return
unique_ptrfrom factories, since callers can promote it toshared_ptrbut can't demote.
Advanced
14. Is shared_ptr thread-safe?
It is partly thread-safe, and this is one of the most misunderstood areas.
Thread-safe:
- The reference counts are updated atomically. Different
shared_ptrinstances that share a control block can be copied, destroyed and reset concurrently from different threads.
NOT thread-safe:
- The pointed-to object. You still need your own synchronization for the data.
- Modifying the same
shared_ptrinstance from multiple threads (for example assigning to it in one thread while another copies it). That is a data race on the pointer itself.
std::shared_ptr<Config> g_cfg;
// Thread A
g_cfg = std::make_shared<Config>(newCfg); // writes g_cfg
// Thread B
auto local = g_cfg; // reads g_cfg => DATA RACE
Fix: std::atomic<std::shared_ptr<T>> (C++20):
std::atomic<std::shared_ptr<Config>> g_cfg;
g_cfg.store(std::make_shared<Config>(newCfg)); // writer
auto local = g_cfg.load(); // reader gets a safe snapshot
Notes:
- The older free functions (
std::atomic_load(&sp)and friends) are deprecated since C++20 and removed in C++26. Preferatomic<shared_ptr>. atomic<shared_ptr>is typically not lock-free in mainstream implementations, so it is great for rarely updated configuration, but not for a hot read path.use_count()is only an approximation in multithreaded code. Never base logic on it.
Interview takeaway: "The control block is thread-safe; the object and the
shared_ptrvariable are not." Know theatomic<shared_ptr>fix.
15. What are the performance costs of shared_ptr, and how do you mitigate them?
Costs:
- Atomic reference-count operations on every copy and destruction. Under multi-thread contention, the control block's cache line bounces between cores.
- Extra indirection and memory (the control block, plus a second allocation unless you use
make_shared). weak_ptr::lock()does a compare-and-swap loop to safely increment a count that might be zero.atomic<shared_ptr>is typically lock-based.
Mitigations:
- Prefer
unique_ptror plain values. Don't useshared_ptrby default. - Pass by reference (
const T&,T&), not byshared_ptrvalue, when you don't need ownership:void process(const Widget& w); // zero refcount traffic // not: void process(std::shared_ptr<Widget> w); // atomic inc + dec per call - Move
shared_ptrs when transferring ownership (no atomic traffic):queue.push(std::move(sp)); - Use
make_sharedfor one allocation and better locality. - Hoist copies out of hot loops (copy once, then use the raw reference).
- For read-mostly shared data in hot paths, consider alternatives: a raw pointer with a well-defined lifetime, hazard pointers/RCU, or double buffering.
Interview takeaway: A
shared_ptrcopy is "a pair of atomic read-modify-write operations on shared memory". It is cheap in isolation, but expensive when many threads copy the same pointer.
16. What are the moved-from states, and what are the common get() / reset() / release() mistakes?
Moved-from state: a moved-from unique_ptr and a moved-from shared_ptr are both guaranteed to be null (empty). It is safe to assign to or destroy them, and to test them.
auto a = std::make_unique<int>(1);
auto b = std::move(a);
if (!a) { /* a is null: guaranteed */ }
Classic mistakes:
// 1. Two owners from one raw pointer: double delete
auto p = std::make_shared<int>(1);
std::shared_ptr<int> q(p.get()); // BUG: separate control block
// 2. release() leaks if you ignore the result
std::unique_ptr<int> u = std::make_unique<int>(1);
u.release(); // BUG: nobody deletes it now
// 3. Handing ownership of get() to something else
delete u.get(); // BUG: u will delete it again
// 4. Using get() beyond the owner's lifetime
int* raw = std::make_unique<int>(1).get(); // BUG: dangling immediately
// 5. new[] with the wrong smart pointer
std::unique_ptr<int> bad(new int[10]); // BUG: calls delete, not delete[]
Rules:
get()gives a non-owning view. Don't store it past the owner, and never delete it or give it to another owning smart pointer.release()relinquishes ownership; you must take responsibility for the returned pointer.reset()deletes the current object (and optionally adopts a new one).- Don't write
return std::move(local_unique_ptr);. It is unnecessary and can inhibit copy elision.
17. Is weak_ptr safe across threads? What is the expired() / lock() race?
weak_ptr::lock() is atomic: it increments the strong count only if it's still above zero, and returns an empty shared_ptr otherwise, so it is safe against concurrent destruction.
The race is in the two-step pattern:
// BAD: time-of-check to time-of-use
if (!weak.expired()) {
auto strong = weak.lock(); // may be null: object could die between the two calls
strong->work(); // potential null dereference
}
// GOOD: one atomic step
if (auto strong = weak.lock()) {
strong->work(); // object is kept alive for this scope
}
Typical use, a cache that doesn't keep objects alive:
std::unordered_map<Key, std::weak_ptr<Resource>> cache;
std::shared_ptr<Resource> get(const Key& k) {
if (auto it = cache.find(k); it != cache.end()) {
if (auto sp = it->second.lock()) return sp; // still alive: reuse
}
auto sp = std::make_shared<Resource>(k); // otherwise load it
cache[k] = sp;
return sp;
}
(The map itself still needs a mutex if shared between threads, and expired entries should be pruned periodically.)
Interview takeaway: Never test
expired()and then act. Uselock()and check the result.
18. What goes wrong when lambdas capture shared_ptr or this?
Capturing a shared_ptr in a lambda extends the object's lifetime to the lifetime of the lambda. That is sometimes intentional and sometimes a leak.
class Session : public std::enable_shared_from_this<Session> {
std::function<void()> onDone_;
public:
void start() {
// BAD: Session owns onDone_, and onDone_ owns Session => cycle, never freed
onDone_ = [self = shared_from_this()] { self->finish(); };
// GOOD: the callback holds only a weak reference
onDone_ = [weak = weak_from_this()] {
if (auto self = weak.lock()) self->finish();
};
}
void finish();
};
Two distinct patterns:
- Intentional lifetime extension (very common in async networking, as with Asio): pass
shared_from_this()to an async operation so the object survives until the callback runs. The operation, not the object, owns the lambda, so there is no cycle. - Accidental cycle: the object itself stores a callback that captures a
shared_ptrto it. Useweak_ptrin that case.
Capturing this (raw) is a different hazard: if the lambda outlives the object, this dangles. Capture shared_from_this() (to extend the lifetime) or weak_from_this() (to check it) instead.
Interview takeaway: Ask, "who owns the lambda?" If the object owns the lambda that captures it, you have a cycle.
19. How do you store and copy polymorphic objects with smart pointers?
Use std::vector<std::unique_ptr<Base>> for owned polymorphic collections. The vector owns the elements, and unique_ptr's move is noexcept, so reallocation moves cheaply.
std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Circle>(1.0));
shapes.push_back(std::make_unique<Square>(2.0));
for (const auto& s : shapes) s->draw();
The collection is not copyable (since unique_ptr isn't). To support copying, give the base class a virtual clone() and copy explicitly:
struct Shape {
virtual ~Shape() = default;
virtual std::unique_ptr<Shape> clone() const = 0;
virtual void draw() const = 0;
};
struct Circle : Shape {
std::unique_ptr<Shape> clone() const override {
return std::make_unique<Circle>(*this);
}
void draw() const override { /* ... */ }
};
std::vector<std::unique_ptr<Shape>> copyAll(const std::vector<std::unique_ptr<Shape>>& src) {
std::vector<std::unique_ptr<Shape>> out;
out.reserve(src.size());
for (const auto& s : src) out.push_back(s->clone());
return out;
}
Other points:
- Sink-and-store: a function taking
std::unique_ptr<Shape>by value clearly signals it takes ownership. - Variants: for a closed set of types,
std::vector<std::variant<Circle, Square>>avoids per-element heap allocation entirely. - Raw observers: it's fine to keep non-owning
Shape*/Shape&views while the owning vector is alive and not reallocating its contents.
20. When should you NOT use shared_ptr? How do you decide on ownership?
shared_ptr is often over-used as a way to avoid thinking about ownership. A shared owned object has no single owner, so its lifetime becomes unpredictable, destruction can happen on any thread, and cycles and hidden costs creep in.
A decision guide:
- Can it be a value or a member? Do that. No pointers at all.
- Does one object clearly own it? Use
unique_ptr, and hand outT&/T*for non-owning use. - Truly shared ownership (several independent owners, and none outlives the others by design: caches, graphs, async operations keeping state alive)? Use
shared_ptr, withweak_ptrfor back-references and observers. - Non-owning access with a guaranteed lifetime? Use a reference or raw pointer. A raw pointer is fine as an observer (a non-owning
T*is not a smell).
Reasons to avoid shared_ptr by default:
- It hides ownership, because "everyone owns it" is the same as "no one is responsible".
- It makes destruction order and thread non-deterministic (the last owner to release runs the destructor, wherever it is).
- It costs atomic operations and memory (Q15).
- It invites cycles (Q7).
Interview takeaway: "Prefer
unique_ptr; useshared_ptronly when ownership is genuinely shared, and be able to say who the owners are." Many interviewers consider heavyshared_ptruse a design smell.
Coding Questions
21. Implement a simplified unique_ptr
Interviewers use this to check move semantics, the rule of five, deleter handling and noexcept.
template <typename T, typename D = std::default_delete<T>>
class UniquePtr {
T* ptr_ = nullptr;
[[no_unique_address]] D deleter_{};
public:
constexpr UniquePtr() noexcept = default;
explicit UniquePtr(T* p) noexcept : ptr_(p) {}
UniquePtr(T* p, D d) noexcept : ptr_(p), deleter_(std::move(d)) {}
// Not copyable
UniquePtr(const UniquePtr&) = delete;
UniquePtr& operator=(const UniquePtr&) = delete;
// Movable
UniquePtr(UniquePtr&& other) noexcept
: ptr_(std::exchange(other.ptr_, nullptr)),
deleter_(std::move(other.deleter_)) {}
UniquePtr& operator=(UniquePtr&& other) noexcept {
if (this != &other) {
reset(other.release()); // delete ours, adopt theirs
deleter_ = std::move(other.deleter_);
}
return *this;
}
~UniquePtr() { reset(); }
T* release() noexcept { return std::exchange(ptr_, nullptr); }
void reset(T* p = nullptr) noexcept {
T* old = std::exchange(ptr_, p);
if (old) deleter_(old);
}
void swap(UniquePtr& other) noexcept {
std::swap(ptr_, other.ptr_);
std::swap(deleter_, other.deleter_);
}
T* get() const noexcept { return ptr_; }
T& operator*() const { return *ptr_; }
T* operator->() const noexcept { return ptr_; }
explicit operator bool() const noexcept { return ptr_ != nullptr; }
};
Points interviewers look for:
- Copy operations are deleted; move operations are
noexcept(so containers can move elements on reallocation). - Move assignment handles self-assignment and releases the old object.
- The destructor delegates to
reset()so the deleter is used consistently. explicit operator bool(so it doesn't convert implicitly toint).- The deleter is stored with
[[no_unique_address]](or the empty-base optimization) so a stateless deleter costs no space.
22. Sketch the core of shared_ptr and weak_ptr (the control block)
A full implementation is long, so interviewers usually ask for the control block and the reference-counting logic.
struct ControlBlock {
std::atomic<long> strong{1};
std::atomic<long> weak{1}; // +1 held collectively by all strong owners
virtual void destroyObject() noexcept = 0; // runs the deleter / destructor
virtual void destroyBlock() noexcept = 0; // frees the control block itself
virtual ~ControlBlock() = default;
};
inline void releaseWeak(ControlBlock* cb) noexcept {
if (cb->weak.fetch_sub(1, std::memory_order_acq_rel) == 1) {
cb->destroyBlock(); // last weak reference: free the block
}
}
inline void releaseStrong(ControlBlock* cb) noexcept {
if (cb->strong.fetch_sub(1, std::memory_order_acq_rel) == 1) {
cb->destroyObject(); // last owner: destroy the object
releaseWeak(cb); // drop the implicit weak reference
}
}
inline void addStrong(ControlBlock* cb) noexcept {
cb->strong.fetch_add(1, std::memory_order_relaxed); // copying: relaxed is enough
}
// weak_ptr::lock(): increment strong ONLY if it's still non-zero
inline bool tryAddStrong(ControlBlock* cb) noexcept {
long n = cb->strong.load(std::memory_order_relaxed);
while (n != 0) {
if (cb->strong.compare_exchange_weak(n, n + 1, std::memory_order_acq_rel,
std::memory_order_relaxed)) {
return true;
}
}
return false; // object already destroyed
}
Key ideas to explain:
- The strong group holds one weak reference collectively. That keeps the control block alive until both the last strong and the last weak reference are gone.
- Copying a
shared_ptris a relaxed increment (no ordering needed), but releasing needsacq_relso that all prior uses of the object happen before its destruction on whichever thread drops the last reference. weak_ptr::lock()can't blindly increment: the count might be zero. It uses a CAS loop that only succeeds while the strong count is non-zero.- A
make_sharedcontrol block stores the object inline, withdestroyObject()calling the destructor in place anddestroyBlock()freeing the whole allocation, which is why the memory lives on until the weak count reaches zero (Q5).
Quick-Fire Questions
| Question | Short answer |
|---|---|
Can you copy a unique_ptr? |
No. Move it, or clone() the pointee. |
What does shared_ptr::use_count() tell you? |
The number of strong owners. It is only approximate across threads, and never branch on it. |
Does weak_ptr affect use_count()? |
No. It affects only the weak count. |
What does shared_ptr::operator== compare? |
The stored pointers, not the pointed-to values. |
Can shared_ptr hold a nullptr and still own a control block? |
Yes (for example with a custom deleter, or the aliasing constructor with an empty owner). |
Can you put unique_ptr in a std::function? |
Not as a captured move-only lambda (std::function needs copyable). Use std::move_only_function (C++23). |
What's std::owner_less for? |
Ordering smart pointers by ownership (control block), so weak_ptr can be a key in an ordered container. |
Is make_shared<T[]>(n) available? |
Yes, since C++20 (shared_ptr<T[]> itself since C++17). |
How do you avoid zero-filling a big unique_ptr<T[]> buffer? |
std::make_unique_for_overwrite<T[]>(n) (C++20). |
unique_ptr<T> vs T* for ownership in a header? |
unique_ptr<T> documents and enforces ownership. A raw T* should mean "non-owning observer". |
What happens if the deleter of a unique_ptr throws? |
Deleters must not throw. The destructor is noexcept, so it would call std::terminate. |
Why does std::move on a returned local unique_ptr hurt? |
It's redundant (implicit move already applies) and can prevent copy elision (NRVO). |
The 10 to Memorize
| # | Topic | Key point |
|---|---|---|
| 1 | Choosing a smart pointer | Default unique_ptr; shared_ptr only for genuinely shared ownership |
| 2 | unique_ptr cost |
Zero overhead with the default deleter; move-only; release() doesn't delete |
| 3 | shared_ptr internals |
Two pointers; control block with strong + weak counts and a type-erased deleter |
| 4 | weak_ptr and lock() |
Non-owning; always lock(), never expired() then use |
| 5 | make_shared trade-off |
One allocation, but memory outlives the object while weak refs exist |
| 6 | Passing smart pointers | Reference to use; unique_ptr by value to sink; shared_ptr by value to share |
| 7 | Cycles | Back-references, caches and observers are weak_ptr |
| 8 | enable_shared_from_this |
Never shared_ptr<T>(this); needs an existing owner; not in the constructor |
| 9 | Deleters | Part of the type for unique_ptr, type-erased for shared_ptr |
| 10 | Thread safety | Counts are atomic; the object and the same shared_ptr instance are not; atomic<shared_ptr> |
Final thought: for a senior role, the strongest answers go past "what it does" to why: why
unique_ptris free, whyshared_ptris not, whylock()and notexpired(), and who owns what. If you only have time to prepare a few topics in depth, make them Q5 (make_shared trade-offs), Q14 (thread safety), Q15 (performance), Q18 (lambda cycles) and Q20 (ownership design). Those are where interviewers can quickly tell whether you've shipped real systems.
Comments
Post a Comment