C++ memory use_count() Function
Example
Count the owners of the memory:
shared_ptr<int> ptr1 = make_shared<int>(10);
cout << ptr1.use_count() << "\n";
shared_ptr<int> ptr2 = ptr1;
cout << ptr1.use_count();
Definition and Usage
The use_count() function returns the number of shared_ptr variables that own the same memory.
In the example, the count goes from 1 to 2 when ptr2 becomes a copy of ptr1.
The use_count function is defined in the <memory> header file.
Syntax
ptr.use_count();
ptr is a shared_ptr or a weak_ptr.
Parameter Values
None.
Technical Details
| Returns: | A long with the number of owners, or 0 if there are none. |
|---|
Related Pages
Read more about smart pointers in our Smart Pointers Tutorial.