std::shared_ptr::use_count(3)
π NAME π
std::shared_ptr::use_count - std::shared_ptr::use_count
okay so bestie, welcome to the std::shared_ptr::use_count(3) page from the C++ Standard Libary manual π
(yes, that's literally the manual name β "Libary" and all, no cap). This function is lowkey one of the shared-pointer vibe checks: it tells you how many shared_ptrs are holding hands with the same object π«Ά.
β¨ Synopsis β¨
long use_count() const noexcept;
It returns the number of different shared_ptr instances (this one included π) that are managing the current object. If there's no managed object, 0 is returned.
In a multithreaded environment, the value returned by use_count is approximate β typical implementations use a memory_order_relaxed load. So like, it's giving "estimate" energy, not "absolute truth" energy π.
π Parameters π
(none) β zero. nada. no parameters, bestie π«Ά
π¦ Return value π¦
The number of std::shared_ptr instances managing the current object, or 0 if there is no managed object. That's it. That's the whole return value. Slay π
.
πΈ Notes πΈ
β¨ Common use cases include β¨
- comparison with
0β ifuse_countreturns zero, the shared pointer is empty and manages no objects (whether or not its stored pointer isnullptr). π - comparison with
1β ifuse_countreturns1, there are no other owners. The deprecated (since C++17) member functionunique()is provided for this use case. (until C++20) In multithreaded environment, this does not imply that the object is safe to modify because accesses to the managed object by former shared owners may not have completed, and because new shared owners may be introduced concurrently, such as bystd::weak_ptr::lock.
π Example π
// Run this code
#include <iostream>
#include <memory>
void fun(std::shared_ptr<int> sp)
{
std::cout << "in fun(): sp.use_count() == " << sp.use_count()
<< " (object @ " << sp << ")\n";
}
int main()
{
auto sp1 = std::make_shared<int>(5);
std::cout << "in main(): sp1.use_count() == " << sp1.use_count()
<< " (object @ " << sp1 << ")\n";
fun(sp1);
}
π Possible output: π
in main(): sp1.use_count() == 1 (object @ 0x20eec30)
in fun(): sp.use_count() == 2 (object @ 0x20eec30)
π See also π
unique(until C++20) β checks whether the managed object is managed only by the currentshared_ptrobject (public member function).
source/version/date vibes: http://cppreference.com Β· 2024.06.10 Β· page: std::shared_ptr::use_count(3) πβ¨
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms