SysTutorials

Linux Manual Pages › Section 3

stdshared_ptruse_count(3)

std::shared_ptr<T>::use_count - std::shared_ptr<T>::use_count

Synopsis

long use_count() const noexcept;

Returns the number of different shared_ptr instances (this included) managing the current object. If there is no managed object, 0 is returned. In multithreaded environment, the value returned by use_count is approximate (typical implementations use a memory_order_relaxed load)

Parameters

(none)

Return value

the number of shared_ptr instances managing the current object or 0 if there is no managed object.

Notes

Common use cases include

Example

// Run this code

#include <memory>
#include <iostream>
void fun(std::shared_ptr<int> sp)
{
std::cout << "fun: sp.use_count() == " << sp.use_count() << ‘\n’;
}
int main()
{
auto sp1 = std::make_shared<int>(5);
std::cout << "sp1.use_count() == " << sp1.use_count() << ‘\n’;
fun(sp1);
}

Output:

  sp1.use_count() == 1   fun: sp.use_count() == 2

See also

unique checks whether the managed object is managed only by the current shared_ptr instance               (public member function) (until C++20)