c++ - boost.enable_shared_from_this 并创建另一个 shared_ptr<T>

标签 c++ boost shared-ptr

最近,我遇到了 boost 智能指针的问题。需要说明的是,enable_shared_from_this 为类 T 保留一个“this”shared_ptr。当 T 的实例超出范围时,enable_shared_from_this 仍然存在。但是如果我创建一个新的原始 ptr 的 shared_ptr 对象呢?有什么区别?

非常感谢。

class Foo : public boost::enable_shared_from_this<Foo>
{};

int main() {
  shared_ptr<Foo> p1(new Foo);
  shared_ptr<Foo> p2 = p1->shared_from_this();
  shared_ptr<Foo> p3 = shared_ptr<Foo>(p1);

  p1.reset();
  // p1 is released, p2 and p3 still remains.
  // but what is the diff between p2 and p3?
  // Can I say shared_from_this() works the same way as
  // shared_ptr<Foo>(p1);
}

最佳答案

当您的新指针超出范围时,它可能会使您的程序崩溃。原因是 shared_ptr 通过计算对对象的引用来控制对象的生命周期。每次复制 shared_ptr 时,它都会增加引用计数,每次 shared_ptr 对象超出范围时,它都会减少引用计数。当引用计数达到零时,它将删除对象。当您在类方法内部创建的 shared_ptr 超出范围时,它将删除它,因为引用计数将为零。

因此,当您在类成员函数中需要一个shared_ptr 时,应该使用shared_from_this,而在任何其他情况下,您可以只使用指向对象的共享指针.

考虑这个例子:

class Y
{
public:

    shared_ptr<Y> f()
    {
        return shared_ptr<Y>(this);
    }
}

如果你在这里返回普通的共享指针,你会创建多个指向同一个指针的shared_ptrs,然后在某个时候删除this,同时保留所有其他指针shared_ptr 实例悬空(指向已删除的内容)。 所以,正确的版本是:

class Y: public enable_shared_from_this<Y>
{
public:

    shared_ptr<Y> f()
    {
        return shared_from_this();
    }
}

关于c++ - boost.enable_shared_from_this 并创建另一个 shared_ptr<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26485005/

相关文章:

c++ - 函数指针的意义何在?

c++ - 用于编译所有文件的 MinGW GCC 通配符 (Windows)

c++ - Boost:错误的模板参数数量

c++11 - shared_ptr<T> 到 const shared_ptr<const T>&

c++ - 如何计算对象和 shared_ptr 的对齐方式?

c++ - 从多个组件构建一个 C++ 类

c++ - CMFCPropertyGridProperty 数字输入

python - C++ Boost Python numpy 数组初始化

c++ - MPI 发送自定义序列化对象(更通用的代码)

c++ - 为什么类的析构函数被调用了两次?共享指针