为什么 shared_ptr 的引用计数对象也需要跟踪指向该对象的 weak_ptrs 的数量?
Why shared_ptr's reference counting object needs to keep track of the number of weak_ptrs pointing to the object too?
您好,我正在通读 this document and some other documents about C++'s shared_ptr
and they all seem to suggest that apart from the number of shared_ptr
pointing to the allocated object, the reference count object has to keep track of how many weak_ptr
pointer pointing to the object as well. My question is why? From my understanding, weak_ptr
is non-owning so if the count of shared_ptr
pointing to the object reaches zero the object can be deleted. That is why sometimes we need to use expired 以检查 weak_ptr
指向的对象的可用性。您能否解释一下需要跟踪 weak_ptr
数量的原因?
这里为什么需要弱计数?
shared_ptr
引用计数是对象所有者的计数。 weak_ptr
引用计数是引用计数控制块所有者的计数。
std::weak_ptr
指的是控制块,以了解对象是否仍然存在,如果存在,则在需要时向其提供 std::shared_ptr
。因此,只要 std::weak_ptr
或 std::shared_ptr
存在,控制块就必须存在。您需要跟踪 std::weak_ptr
的实例数以了解最后一个实例何时被销毁,就像 std::shared_ptr
.
添加 François Andrieux 的回答:
这有一个副作用,理解这一点非常重要。
如果您使用 std::make_shared 的实现,该实现使用 WKWYL 优化(我们知道你住在哪里)将控制块和实际对象一起分配为一个连续分配,内存将不会被释放,直到毕竟 weak_ptr 个对象也超出了范围。
(我的账号很少使用,所以我不能添加评论,由于没有足够的信誉点,因此添加为答案而不是评论)
您好,我正在通读 this document and some other documents about C++'s shared_ptr
and they all seem to suggest that apart from the number of shared_ptr
pointing to the allocated object, the reference count object has to keep track of how many weak_ptr
pointer pointing to the object as well. My question is why? From my understanding, weak_ptr
is non-owning so if the count of shared_ptr
pointing to the object reaches zero the object can be deleted. That is why sometimes we need to use expired 以检查 weak_ptr
指向的对象的可用性。您能否解释一下需要跟踪 weak_ptr
数量的原因?
这里为什么需要弱计数?
shared_ptr
引用计数是对象所有者的计数。 weak_ptr
引用计数是引用计数控制块所有者的计数。
std::weak_ptr
指的是控制块,以了解对象是否仍然存在,如果存在,则在需要时向其提供 std::shared_ptr
。因此,只要 std::weak_ptr
或 std::shared_ptr
存在,控制块就必须存在。您需要跟踪 std::weak_ptr
的实例数以了解最后一个实例何时被销毁,就像 std::shared_ptr
.
添加 François Andrieux 的回答:
这有一个副作用,理解这一点非常重要。
如果您使用 std::make_shared 的实现,该实现使用 WKWYL 优化(我们知道你住在哪里)将控制块和实际对象一起分配为一个连续分配,内存将不会被释放,直到毕竟 weak_ptr 个对象也超出了范围。
(我的账号很少使用,所以我不能添加评论,由于没有足够的信誉点,因此添加为答案而不是评论)