c++ - 来自同一个 enable_shared_from_this 实例的两个 shared_ptr

标签 c++ shared-ptr reference-counting weak-ptr enable-shared-from-this

鉴于这个类是enable_shared_from_this:

class connection : public std::enable_shared_from_this<connection>
{
   //...
};

假设我从 same connection* 创建了两个 std::shared_ptr 实例,如下所示:

std::shared_ptr<connection> rc(new connection);

std::shared_ptr<connection> fc(rc.get(), [](connection const * c) {
                                   std::cout << "fake delete" << std::endl;
                               });

到目前为止一切正常,因为资源 { connection* } 由单个 shared_ptrrc 准确地说,fc 只是有一个假的删除器。

之后,我这样做:

auto sc = fc->shared_from_this();
//OR auto sc = rc->shared_from_this(); //does not make any difference!

现在 shared_ptrrcfcsc 将共享其 reference-count 与?换句话说,

std::cout << rc->use_count() << std::endl;
std::cout << fc->use_count() << std::endl;

这些应该打印什么?我测试了这段代码和 found rc 似乎有 2 引用,而 fc 只有 1

我的问题是,这是为什么?什么是正确的行为及其理由

我使用的是 C++11 和 GCC 4.7.3

最佳答案

The raw pointer overloads assume ownership of the pointed-to object. Therefore, constructing a shared_ptr using the raw pointer overload for an object that is already managed by a shared_ptr, such as by shared_ptr(ptr.get()) is likely to lead to undefined behavior, even if the object is of a type derived from std::enable_shared_from_this. -- http://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr

在您的情况下,您得到的共享指针具有两个不同的所有权信息 block ,但始终会增加该类的第一个共享指针实例的引用计数。

如果您删除“假删除器”,您会遇到双重免费问题。

关于c++ - 来自同一个 enable_shared_from_this 实例的两个 shared_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47257218/

相关文章:

c++ - 如何创建 shared_ptr 的容器到抽象类

c++ - std::shared_ptr 在空指针上调用非默认删除器

c++ - 我们如何将嵌套的 if else 与 #define 预处理器一起使用

c++ - 如何从Qt中的字符串中获取特定字段的值

c++ - 如何找到 Windows PC 的共享数据/文件夹?

rust - 是否有针对 Rc 或 Arc 的操作可以克隆基础值并将其返回给调用者?

python - 为什么对 Python 值(即函数参数)的引用存储在 CPython 中的堆栈(帧)上?

c++ - 将输出流对象和其他参数传递给多个线程

c++ - CRTP 模式和 enable_shared_from_this

c++ - 为什么在调用构造函数后会崩溃?我正在尝试将shared_ptr推回 vector