weak_ptr::use_count
条目包含警告:
此函数的用法和行为与
类似,但它返回不同的计数。std::shared_ptr::use_count
既然它应该计算有多少个
shared_ptr
实例共享指针的所有权,那么在什么情况下它可以返回不同的计数?
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,它是社区策划的。通常它与标准中的文本相当接近。但我在标准中没有找到与此注释类似的内容。