KatInterview

Strong vs Weak Counts in shared_ptr and How weak_ptr Breaks Cycles

Data Structure DesignModel answer
MediumModel answerData Structure Designcppsmart-pointersshared_ptr

Last updated

Describe the two reference counts in a shared_ptr control block, how weak_ptr uses them, why lock() is needed, and how a weak back-edge fixes a leaking ownership cycle.

Question

A C++ std::shared_ptr<T> does not track ownership inside the object itself. It uses a separate heap-allocated control block that stores two counters. Explain how that control block works and how std::weak_ptr<T> fits into it.

Your answer should cover:

  1. The two counters. What does the strong count measure, and what does the weak count measure?
  2. Two different lifetimes. What exactly happens when the strong count reaches zero, and what happens later when the weak count reaches zero?
  3. Why lock() exists. A weak_ptr cannot be dereferenced directly. Explain why a check followed by a use is unsafe in a multithreaded program, and how lock() avoids the problem.
  4. Cycle breaking. Explain how a weak_ptr stops a leak when two objects point at each other.

Scenario

Consider a list-like node type:

struct Node {
    std::shared_ptr<Node> next;   // owning link
    std::weak_ptr<Node>   prev;   // non-owning link
};

Suppose node A refers to B through next, and B refers back to A. Describe what goes wrong if the link from B back to A is also a shared_ptr. Then walk through the order in which strong counts, weak counts, destructors and control blocks change when the back-link is a weak_ptr, and both local handles to A and B go out of scope.

State any caveats you consider important, such as what the thread-safety guarantee does and does not cover.

Hints

Hint 1

Destroying the managed object and freeing the control block are two separate events, and each is driven by a different counter.

Hint 2

Think about what a weak_ptr must still be able to read after the object is gone. That tells you why the control block has to outlive the object.

Hint 3

For lock(), consider an atomic 'increment only if the current value is not zero'. Why can this never resurrect a destroyed object?

Hint 4

In the cycle example, trace the strong count of each node after the local handles are dropped. Which count never reaches zero when both links are owning?