Breaking shared_ptr Cycles

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

class B;

class A {
public:
    // A needs access to B and currently owns it
    shared_ptr<B> b;

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

class B {
public:
    // B also needs access to A
    // Question to consider:
    // Does B really need to OWN A?
    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;
        objB->a = objA;

        // At this point:
        // objA owns objB
        // objB owns objA
        // Think about what happens to reference counts
    }

    // If ownership is correct, destructors should run before this
    cout << "End of scope" << endl;
    return 0;
}

Solving Approach

 

 

 

 

Upvote
Downvote
Loading...

Input

Expected Output

A destroyed B destroyed End of scope