c++如何传递类实例的boost共享指针到嵌套类对象

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

本文关键字:指针 嵌套 对象 共享 何传递 实例 c++ boost      更新时间:2023-10-16

我们有(伪代码):

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

是否有可能在c++中使用shared_ptr做这样的事情,以及如何在实际的c++代码中做到这一点?

您需要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())) { }
};

(这适用于c++ 0x;Boost的工作原理类似)

仅仅从this中创建一个共享指针是棘手的,因为您可能会把自己的脚射掉。继承enable_shared_from_this使这更容易。

警告:您使用裸A指针的构造似乎违背了使用资源管理类的目的。为什么不把a也变成一个智能指针呢?也许是unique_ptr ?