【问题标题】:What happens when we reset a shared_ptr when there are other shared_ptr alias constructed from it?当我们重置一个 shared_ptr 并且有其他 shared_ptr 别名由它构造时会发生什么?
【发布时间】:2021-08-25 08:41:08
【问题描述】:

我目前正在学习shared_ptr的别名构造函数,我写的代码是这样的

int main(){
    std::shared_ptr<Father> father = std::make_shared<Father>();
    std::shared_ptr<Son> son(father, &father->son);
    printf("%d\n", father.use_count());
    printf("%d\n", son.use_count());
    father.reset();
    printf("%d\n", father.use_count());
    printf("%d\n", son.use_count());
    printf("%d\n", father.owner_before(son));
    printf("%d\n", son.owner_before(father));
    return 0;
}

然后打印出来

2
2
0
1
1
0

我在这里迷路了。在我看来,father.reset() 之后,father 应该仍然有 use_count = 1 而不是 0,因为儿子是从父亲构造的别名,并且它没有被破坏。从this post,作者还说father.use_count()是1。

// Foo 仍然存在 (ref cnt == 1) // 所以我们的 Bar 指针仍然有效,我们可以用它来做东西

那么为什么printf("%d\n", father.use_count()); 打印出来是0?

【问题讨论】:

  • “从这篇文章中,作者还说father.use_count() 是1” - 没有这样的说法。你的困惑源于糟糕的命名。您将指针与它们管理的对象混为一谈。
  • 他说“Foo 仍然存在 (ref cnt == 1)”
  • 是的,Foo。他并没有说复位指针的use_count 仍然神奇地指向一个被告知要忘记的对象。
  • OK,所以一旦shared_ptr被重置,它就无法访问Foo。那么还有其他方法可以检查 Foo 是否仍然存在?例如,跟踪Foo::~Foo?
  • 是的。追踪 d'tor 会告诉你物体何时消失

标签: c++ shared-ptr smart-pointers


【解决方案1】:

father.reset() 之后,father 不指向任何东西。它拥有一个空值(官方称“没有托管对象”)。

您正在打印什么都没有的use_count,而不是FatherSon 对象的use_count,以及the use_count of a null pointer is 0

【讨论】:

    猜你喜欢
    • 2016-03-06
    • 1970-01-01
    • 2012-08-08
    • 1970-01-01
    • 2020-06-17
    • 1970-01-01
    • 2017-05-29
    • 2020-05-31
    相关资源
    最近更新 更多