std::weak_ptr<T>::use_count

来自cppreference.com
< cpp‎ | memory‎ | weak ptr
 
 
内存管理库
(仅用于阐述*)
分配器
未初始化内存算法
受约束的未初始化内存算法
内存资源
未初始化存储 (C++20 前)
(C++17 弃用)
(C++17 弃用)

垃圾收集器支持 (C++23 前)
(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: ??

[编辑] 参阅

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