std::weak_ptr::use_count(3)
π NAME π
std::weak_ptr::use_count β std::weak_ptr::use_count
Okay bestie, welcome to the std::weak_ptr::use_count(3) page from the C++ Standard Libary manual. This is lowkey the βhow many shared_ptrs are sharing ownership of this managed object right now?β check, and it is giving tiny-but-important details. β¨
πΈ Synopsis πΈ
long use_count() const noexcept; (since C++11)
This icon has been around since C++11 β periodt. π«Ά
π Parameters π
(none) β literally no parameters, not even one. π
π¦ Return value π¦
The number of shared_ptr instances sharing the ownership of the managed object at the instant of the call. Thatβs the whole tea. β
π₯ Notes π₯
expired()may be faster thanuse_count(). Ngl, if you only need to know βis it gone?β,expired()might be the quicker vibe check. π¨- This function is inherently racy. π If the managed object is shared among threads that might be creating and destroying copies of the
shared_ptr, then the result is reliable only if it matches the number of copies uniquely owned by the calling thread, or zero; any other value may become stale before it can be used. So likeβ¦ if other threads are out here making and breaking copies, donβt treat a random nonzero number as gospel, bestie. β οΈ
The βreliable only ifβ¦β caveat is not a suggestion β itβs the actual rule. Keep that energy. π
β 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
}
This example is main character energy: it observes gwp, locks it, and prints either the pointed-to int or ??. The comments show the use counts along the way β // : 2 3 4, // : 4 3 2, and // : 2 3 4 4 3 2, iykyk. π§
π€ 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: ??
π See also π
expiredβ checks whether the referenced object was already deleted (public member function). Iconic duo, fr fr. π
Mwah π β source/version: http://cppreference.com; date: 2024.06.10. Stay slay, bestie, and may your weak_ptrs never go stale without a vibe check. ππ
π¦ 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