Search code examples
c++classboostshared-ptr

C++ how to pass a boost shared pointer of this instance of class to nested class object?


So we have (pseudo code):

class A
{
 A(shared_ptr parent){}
}

class B
{
 A *a;
 B()
 {
  a = new A(boost::shared_ptr(this));
 }
}

Is it possible to do such thing with shared_ptr in C++ and how to do it in real C++ code?


Solution

  • You need enable_shared_from_this:

    #include <memory>
    
    class B : public std::enable_shared_from_this<B>
    {
      A * a;
    public:
      B() : a(new A(std::shared_from_this())) { }
    };
    

    (This is for C++0x; Boost should work similarly.)

    Just making a shared pointer from this is tricky because you might shoot your own foot off. Inheriting from enable_shared_from_this makes this easier.

    Word of warning: Your construction with the naked A pointer seems to defeat the purpose of using resource-managing classes. Why not make a into a smart pointer, too? Maybe a unique_ptr?