简体   繁体   中英

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

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).

Eg

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

As the other response has pointer out, first you'll have to use the enable_shared_from_this to get the shared_ptr , but then the child can't hold that ref, it must use a weak_ptr . A weak_ptr is just like a shared_ptr except that it won't hold a reference until you call the get() method, which will return you a normal shared_ptr which you should get rid of as soon as you can inside the child.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM