当我们重置一个 shared_ptr 而有其他 shared_ptr 别名由它构造时会发生什么?

What happens when we reset a shared_ptr when there are other shared_ptr alias constructed from it?

我目前正在学习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,因为son是从father构造出来的别名,并没有被析构。来自this post,作者还说father.use_count()是1.

// the Foo still exists (ref cnt == 1) // so our Bar pointer is still valid, and we can use it for stuff

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

father.reset()之后,father没有指向任何东西。它包含一个空值(正式“没有托管对象”)。

您正在打印空的 use_count,而不是 FatherSon 对象的 use_count,以及 the use_count of a null pointer is 0.