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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With