Boost shared_ptr and 'this'

I have two classes with parent-child relationships (client and order catalog and file, etc.)

I have

typedef boost::shared_ptr<Parent> ParentPtr

and in the parent class, the method of creating the child

I need child instances to have pointers to their parent.

class Child
{
 ....
     ParentPtr m_parent;
 ....
}

I want it to be shared_ptr so that the parent does not disappear while there are existing children. I also have other people having ParentPtrs for the parent (factory method for parents returns ParentPtr)

Question: how can I give my child ParentPtr

attempt (1). In Parent :: ChildFactory

child->m_parent.reset(this);

this leads to very bad things. There are currently 2 ParentPtr chains pointing to the parent; the result is a premature death of the parent

attempt (2). Parent has

ParentPtr m_me;

which is copied from the return value of the factory parent. Therefore i can do

child->m_parent = m_me;

,

+5
2

, enable_shared_from_this : http://live.boost.org/doc/libs/1_43_0/libs/smart_ptr/enable_shared_from_this.html

boost::enable_shared_from_this, shared_from_this() -, , this ( , ).

.

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

, enable_shared_from_this, shared_ptr, ref, weak_ptr. A weak_ptr shared_ptr, , , get(), shared_ptr, , .

0

All Articles