【发布时间】: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