std::weak_ptr<T>::use_count
自 C++11 起
long use_count() const noexcept;
返回共享管理对象所有权的 shared_ptr 实例的数量,如果管理对象已被删除,则返回 0,即 *this
为空。
参数
(无)
返回值
调用时共享管理对象所有权的 shared_ptr 实例的数量。
备注
expired() 可能比 use_count() 更快。此函数本质上是竞态的,如果管理对象在可能创建和销毁 shared_ptr 副本的线程之间共享:那么,结果只有在它与调用线程唯一拥有的副本数量匹配时才可靠,或者为零;任何其他值在可以使用之前都可能过时。
示例
#include <iostream>
#include <memory>
std::weak_ptr<int> gwp;
void observe_gwp() {
std::cout
<< "use_count(): "
<< gwp.use_count() << "\t id: ";
if (auto sp = gwp.lock())
std::cout << *sp << '\n';
else
std::cout << "??\n";
}
void share_recursively(std::shared_ptr<int> sp, int depth) {
observe_gwp(); // : 2 3 4
if (1 < depth)
share_recursively(sp, depth - 1);
observe_gwp(); // : 4 3 2
}
int main() {
observe_gwp();
{
auto sp = std::make_shared<int>(42);
gwp = sp;
observe_gwp(); // : 1
share_recursively(sp, 3); // : 2 3 4 4 3 2
observe_gwp(); // : 1
}
observe_gwp(); // : 0
}
结果
use_count(): 0 id: ??
use_count(): 1 id: 42
use_count(): 2 id: 42
use_count(): 3 id: 42
use_count(): 4 id: 42
use_count(): 4 id: 42
use_count(): 3 id: 42
use_count(): 2 id: 42
use_count(): 1 id: 42
use_count(): 0 id: ??