Search code examples
c++boostshared-ptr

boost shared_ptr and 'this'


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


Solution

  • I'm fairly sure that enable_shared_from_this solves your problem: http://live.boost.org/doc/libs/1_43_0/libs/smart_ptr/enable_shared_from_this.html

    If you derived your class from a specialization of boost::enable_shared_from_this then you can use shared_from_this() in a member function to obtain the shared pointer that owns this (assuming that there is one).

    E.g.

    class Parent : public boost::enable_shared_from_this<Parent>
    {
        void MakeParentOf(Child& c)
        {
            c.m_parent = shared_from_this();
        }
    };