Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 841
pm100 Avatar asked Jul 12 '10 16:07

pm100


People also ask

What is boost shared_ptr?

Starting with Boost release 1.53, shared_ptr can be used to hold a pointer to a dynamically allocated array. This is accomplished by using an array type ( T[] or T[N] ) as the template parameter.

Should I use unique_ptr or shared_ptr?

Use unique_ptr when you want to have single ownership(Exclusive) of the resource. Only one unique_ptr can point to one resource. Since there can be one unique_ptr for single resource its not possible to copy one unique_ptr to another. A shared_ptr is a container for raw pointers.

What is the difference between shared_ptr and Weak_ptr?

The only difference between weak_ptr and shared_ptr is that the weak_ptr allows the reference counter object to be kept after the actual object was freed. As a result, if you keep a lot of shared_ptr in a std::set the actual objects will occupy a lot of memory if they are big enough.

What is the difference between Make_shared and shared_ptr?

The difference is that std::make_shared performs one heap-allocation, whereas calling the std::shared_ptr constructor performs two.


1 Answers

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();
    }
};
like image 151
CB Bailey Avatar answered Sep 30 '22 00:09

CB Bailey