Questions / Quant development, C++ ownership & memory

A cycle can keep objects alive

Applied, about 6 minutes. Question D012.

Each node holds a shared_ptr to the other. How many destructors have run at the print?

int destroyed = 0;
struct Node { std::shared_ptr<Node> next; ~Node() { ++destroyed; } };
auto a = std::make_shared<Node>(), b = std::make_shared<Node>();
a->next = b; b->next = a;
a.reset(); b.reset();
std::cout << destroyed;

Answer it in the app It's free. You get hints, a second try if you miss, and a follow-up question.

Show the answer and worked solution

Answer: 0 destructor calls

  1. Each node starts with one outside owner and gains one owner from the other node.
  2. Resetting both outside handles leaves each count at 1, held by the other node.
  3. No count reaches zero, so no destructor runs and both nodes leak.

Interview shortcut. Cycle: each count stays at 1, nothing is destroyed.

Takeaway. A shared_ptr cycle keeps every member alive.

In the app this has a follow-up where one thing about the setup changes. Try the follow-up.

More c++ ownership & memory questions