开发者

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(sh开发者_JS百科ared_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?


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜