为什么weak_ptr::use_count可能会向shared_ptr::use_count返回不同的计数?

问题描述 投票:0回答:1

cppreference.com 的

weak_ptr::use_count
条目包含警告:

此函数的用法和行为与

std::shared_ptr::use_count
类似,但它返回不同的计数。

既然它应该计算有多少个

shared_ptr
实例共享指针的所有权,那么在什么情况下它可以返回不同的计数?

c++ shared-ptr smart-pointers weak-ptr
1个回答
0
投票

c++标准草案中的文字是:

long use_count() const noexcept;

如果

0
为空,则返回:
*this
;否则,与
shared_ptr
共享所有权的
*this
实例的数量。

我想,该注释试图说明的是

weak_ptr::use_count
不能简单地返回创建它的
std::shared_ptr
s
count
的值。当所有共享指针消失后,
std::weak_ptr::use_count
仍然可以被调用并返回
0

不要忘记 cppreference 是一个 wiki,它是社区策划的。通常它与标准中的文本相当接近。但我在标准中没有找到与此注释类似的内容。

© www.soinside.com 2019 - 2024. All rights reserved.