Search code examples
c++shared-ptrcircular-reference

Destructor from mutually recursive class with shared_from_this not called


I have two classes, A and B, that have a shared_ptr pointing to each other (A has a shared_ptr to B, B has a shared_ptr to A).

I'm trying to have the destructor of both classes called when getting out of the scope, but it doesn't work. No destructor is called.

Here's an example code:

class B;

class A
{
    public:
        A() { std::cout << "Constructor A" << std::endl; }
        ~A() { std::cout << "Destructor A" << std::endl; }

        std::shared_ptr<B> b;
};

class B
{
    public:
        B() { std::cout << "Constructor B" << std::endl; }
        ~B() { std::cout << "Destructor B" << std::endl; }

        std::shared_ptr<A> a;
};

int main()
{
    std::shared_ptr<A> a = std::make_shared<A>();
    a->b = std::make_shared<B>();

    a->b->a = a;
}

How could I fix this?


Solution

  • Remove the circular reference.

    An object that's managed by smart pointers gets destroyed only when the last reference to the object goes out of scope, with the last, remaining shared pointer responsible for deleteing and destroying the object.

    Your code sets up a circular reference: a pair of objects that point to each other using a smart pointer. As such, there's always a smart pointer that's going to reference the other object, with each object's shared pointer preventing the other object from getting destroyed.

    Until this circular reference is broken, these objects will not be destroyed.