ProgrammingHardProduct-company placement · C++

Two classes hold shared_ptr members pointing to each other (a parent owns its child and the child owns its parent). What happens when the last outside shared_ptr to them is destroyed?

  1. A. Neither object is destroyed: each keeps the other's reference count above zero (a leak); one link should be a weak_ptr
  2. B. Both are destroyed, child first
  3. C. Both are destroyed, parent first
  4. D. std::terminate is called because of the cycle

Correct answer: A. Neither object is destroyed: each keeps the other's reference count above zero (a leak); one link should be a weak_ptr

Reference counting cannot reclaim cycles. Making the back-pointer a weak_ptr breaks the ownership cycle while still allowing access via lock().

More OOP with C++ and Java questions

Exams that ask this topic