I have two classes with a parent-child relationship (customer&order directory&file etc)
I have
typedef boost::shared_ptr<Parent> ParentPtr
and in parent class a method to make a child
I need child instances to have pointers to their parent.
class Child
{
....
ParentPtr m_parent;
....
}
I want it to be a shared_ptr so that the parent doesn't disappear while there are existing children. I also have other people holding ParentPtrs to the parent (the factory method for Parents returns a ParentPtr)
Question: how can give the child a ParentPtr
attempt (1) . In Parent::ChildFactory
child->m_parent.reset(this);
this results in very bad things. There are now 2 ParentPtr 'chains' pointing at the parent; result is premature death of Parent
attempt (2). Parent has
ParentPtr m_me;
which is copied from the return value of the Parent factory. So I can do
child->m_parent = m_me;
But now Parent never dies because it holds a reference to itself