std::weak_ptr<T>::use_count
来自cppreference.com
long use_count() const noexcept; |
(C++11 起) | |
返回共享被管理对象所有权的 shared_ptr
实例数量,或若被管理对象已被删除,即 *this 为空时返回 0。
参数
(无)
返回值
共享被管理对象所有权的 shared_ptr
实例数量。
注解
该函数的用法和行为类似 std::shared_ptr::use_count,但返回不同的计数。
示例
运行此代码
#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: ??
参阅
检查被引用的对象是否已删除 (公开成员函数) |