Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

weak_ptr and parent-child cyclic dependencies

I currently have something similar to the following:

class Parent
{
    //just a single child... for sake of simplicity
    //no other class holds a shared_ptr reference to child
    shared_ptr<Child> _child; 
    System * getSystem() {...}
}

class Child
{
    weak_ptr<Parent> _parent;
    ~Child 
    { 
        _parent.lock()->getSystem()->blah(); 
    }
}

The Child destructor always crashes, since when ~Child() runs _parent is always expired. Is there a typical solution to this weirdness?

In short, is there a way to not destroy _parent until ~Child finishes?

like image 546
jameszhao00 Avatar asked Feb 25 '23 13:02

jameszhao00


1 Answers

Since by the time the destructor for the the child gets called, the parent's destructor has already run (dtors for member objects get run after the dtor for the containing object), even if the child was holding a plain pointer to the parent, calling the parent's member function would be invalid by the time ~Child() was called.

You might be able to work around this by having Child call getSystem() at some earlier point and cache the result. Maybe in the constructor of Child (if it has a reference to the parent at the time) or maybe there can be an interface added so that Parent can let the child know it needs to collect whatever it might need during destruction from the parent at that time.

I understand that neither of these is a great solution (it increases coupling of the objects) -hopefully someone will post a better option.

like image 146
Michael Burr Avatar answered Mar 05 '23 23:03

Michael Burr