std::weak_ptr<T>::use_count

来自cppreference.com
< cpp‎ | memory‎ | weak ptr
 
 
工具库
语言支持
类型支持(基本类型、RTTI)
库功能特性测试宏 (C++20)
动态内存管理
程序工具
协程支持 (C++20)
变参数函数
调试支持
(C++26)
三路比较
(C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
通用工具
日期和时间
函数对象
格式化库 (C++20)
(C++11)
关系运算符 (C++20 中弃用)
整数比较函数
(C++20)(C++20)(C++20)   
(C++20)
交换类型运算
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
常用词汇类型
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
初等字符串转换
(C++17)
(C++17)

 
动态内存管理
未初始化内存算法
受约束的未初始化内存算法
分配器
垃圾收集器支持
(C++11)(C++23 前)
(C++11)(C++23 前)
(C++11)(C++23 前)
(C++11)(C++23 前)
(C++11)(C++23 前)
(C++11)(C++23 前)



 
 
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: ??

参阅

检查被引用的对象是否已删除
(公开成员函数)