名前空間
変種
操作

std::weak_ptr<T>::use_count

From cppreference.com
< cpp‎ | memory‎ | weak ptr
 
 
メモリ管理ライブラリ
(説明用*)
未初期化メモリのアルゴリズム
(C++17)
(C++17)
(C++17)
制約付き未初期化
メモリアルゴリズム
Cライブラリ

アロケータ
メモリリソース
ガベージコレクションのサポート
(C++11)(C++23まで)
(C++11)(C++23まで)
(C++11)(C++23まで)
(C++11)(C++23まで)
(C++11)(C++23まで)
(C++11)(C++23まで)
未初期化ストレージ
(C++20まで*)
(C++20まで*)
明示的な生存期間管理
 
 
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: ??

[編集] 関連項目

参照されたオブジェクトが既に削除されたかどうかを確認する
(public メンバ関数) [編集]
English 日本語 中文(简体) 中文(繁體)