Breaking shared_ptr Cycles

#include <iostream>
#include <memory>
using namespace std;

class B;

class A {
public:
    // A owns B
    shared_ptr<B> b;

    ~A() {
        cout << "A destroyed" << endl;
    }
};

class B {
public:
    // B references A but does NOT own it.
    // This breaks the reference cycle.
    weak_ptr<A> a; 

    ~B() {
        cout << "B destroyed" << endl;
    }
};

int main() {
    {
        auto objA = make_shared<A>();
        auto objB = make_shared<B>();

        // Establish mutual relationship
        objA->b = objB; // Reference count of B becomes 1
        objB->a = objA; // Reference count of A stays 1 (weak_ptr doesn't increase it)

        // When this block ends:
        // 1. objA goes out of scope. Ref count of A becomes 0.
        // 2. A is destroyed, which triggers the destruction of its member 'b'.
        // 3. Ref count of B becomes 0, and B is destroyed.
    }

    cout << "End of scope" << endl;
    return 0;
}

Solving Approach

 

 

 

 

Upvote
Downvote
Loading...

Input

Expected Output

A destroyed B destroyed End of scope