C++如何将此类实例的boost共享指针传递给嵌套类对象?

Rel*_*lla 0 c++ boost class shared-ptr

所以我们有(伪代码):

class A
{
 A(shared_ptr parent){}
}

class B
{
 A *a;
 B()
 {
  a = new A(boost::shared_ptr(this));
 }
}
Run Code Online (Sandbox Code Playgroud)

是否可以在C++中使用shared_ptr进行此类操作以及如何在真正的C++代码中执行此操作?

Ker*_* SB 6

你需要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())) { }
};
Run Code Online (Sandbox Code Playgroud)

(这适用于C++ 0x; Boost的工作方式应该类似.)

只是制作一个共享指针this是棘手的,因为你可能会自己开枪.继承enable_shared_from_this使这更容易.

警告:您使用裸A指针构建似乎打败了使用资源管理类的目的.为什么不做成a智能指针呢?也许是unique_ptr