std::weak_ptr<T>::use_count
From cppreference.com
C++
Feature test macros (C++20)
Concepts library (C++20)
Metaprogramming library (C++11)
Ranges library (C++20)
Filesystem library (C++17)
Concurrency support library (C++11)
Execution control library (C++26)
Memory management library
(exposition only*)
(C++11)
(C++23)
(C++11)
(C++17)
(C++11)
(C++11)
(C++20)
(C++20)
(C++17)
(C++11)
(C++17)
(C++20)
(C++17)
(C++17)
(C++17)
(C++17)
(C++17)
(C++17)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++17)
(C++17)
(C++17)
(C++17)
(C++17)
(C++17)
(C++17)
(C++17)
Uninitialized storage (until C++20)
(until C++20*)
(until C++20*)
(until C++20*)
Garbage collector support (until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)
(C++11)
(C++17)
(C++20)
(C++17)
(C++11)
(C++11)
(C++11)
(until C++17*)
(C++11)
(C++17)
(C++26)
(C++26)
(C++11)
(C++11)
(C++11)
(C++23)
(C++23)
(C++11)
(C++20)
(C++11)
(C++11)
(C++20)
(C++26)
std::weak_ptr
Member functions
Modifiers
Observers
weak_ptr::use_count
(C++26)
(C++26)
Non-member functions
Helper classes
(C++20)
Deduction guides (C++17)
long use_count() const noexcept;
(since C++11)
Returns the number of shared_ptr
instances that share ownership of the managed object, or 0 if the managed object has already been deleted, i.e. *this is empty.
Contents
[edit] Parameters
(none)
[edit] Return value
The number of shared_ptr
instances sharing the ownership of the managed object at the instant of the call.
[edit] Notes
The usage and behavior of this function are similar to std::shared_ptr::use_count , but it returns a different count.
[edit] Example
Run this code
#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 }
Output:
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: ??