【问题标题】:C++ how to pass a boost shared pointer of this instance of class to nested class object?C ++如何将此类实例的boost共享指针传递给嵌套类对象?
【发布时间】:2011-08-09 02:07:15
【问题描述】:

所以我们有(伪代码):

class A
{
 A(shared_ptr parent){}
}

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

是否可以在 C++ 中使用 shared_ptr 做这样的事情,以及如何在真正的 C++ 代码中做到这一点?

【问题讨论】:

    标签: c++ class boost shared-ptr


    【解决方案1】:

    你需要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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-03
      • 2022-01-08
      • 1970-01-01
      相关资源
      最近更新 更多