std::shared_ptr::use_count

From cppreference.com
< cpp‎ | memory‎ | shared ptr
 
 
Utilities library
Type support (basic types, RTTI, type traits)
Dynamic memory management
Error handling
Program utilities
Variadic functions
Date and time
Function objects
(C++11)
Relational operators
Optional and any
(C++17)
(C++17)
Pairs and tuples
(C++11)
(C++17)
Swap, forward and move
(C++14)
(C++11)
(C++11)
Type operations
(C++11)
(C++17)
 
 
 
long use_count() const;

Returns the number of different shared_ptr instances (this included) managing the current object. If there is no managed object, 0 is returned.

Contents

[edit] Parameters

(none)

[edit] Return value

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

[edit] Exceptions

noexcept specification:  
noexcept
  

[edit] Notes

Common use cases include

  • comparison with 0. If use_count returns zero, the shared pointer is empty and manages no objects (whether or not its stored pointer is null).
  • comparison with 1. If use_count returns 1, there are no other owners, which may indicate that the managed object is safe to modify. The member function unique() is provided for this use case.

[edit] Example

#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

[edit] See also

checks whether the managed object is managed only by the current shared_ptr instance
(public member function)