65. Breaking shared_ptr Cycles

Two objects need to reference each other as part of their design.
However, when both objects own each other using std::shared_ptr, a cyclic ownership is created.

In such a design:

  • The reference count of both objects never reaches zero
  • Destructors are never called
  • Memory is leaked silently

The given program already demonstrates this problem.

Your task is to modify the ownership design so that:

  • The cyclic ownership is removed
  • The objects can still reference each other
  • Destructors are called correctly when the scope ends

What You Must Do:

  • Study the given class relationship
  • Identify which reference should not represent ownership
  • Change the design so only one side owns the other
  • Ensure the program cleans up correctly at scope exit

Program Flow:

  1. Two objects are created inside a local scope
  2. Both objects reference each other
  3. The scope ends
  4. Destructors are expected to run
  5. Currently, destructors do not run due to cyclic ownership

Current Behavior (Buggy):

  • Program exits the scope
  • No destructor messages are printed

Correct Behavior (After Fix):

  • Both destructors are called
  • Then "End of scope" is printed

Example Output (After Fix):

A destroyed
B destroyed
End of scope

 

Constraints:

  • Do not manually delete objects
  • Do not remove the mutual reference requirement
  • Fix must be achieved by correcting ownership semantics
  • Output format must match exactly

 

 

Loading...

Input

Expected Output

A destroyed B destroyed End of scope