std::shared...~shared_ptr(3)
π std::shared_ptr::~shared_ptr π
okay so this is the C++ Standard Library manual page for std::shared_ptr::~shared_ptr, and bestie, it's literally the destructor page β the goodbye era of a shared_ptr. It's giving "last one out turns off the lights" and honestly? Iconic. π
β¨ NAME β¨
std::shared_ptr::~shared_ptr β yes that's the whole name, it's a destructor, they don't do last names π
πΈ SYNOPSIS πΈ
~shared_ptr();
π¦ DESCRIPTION π¦
So here's the vibe check: if *this owns an object, and it's the last shared_ptr owning it, then that object gets destroyed through the owned deleter. Like, the delegation is real β the deleter does the actual work, not us. π«Ά
And after the destruction? All the smart pointers that shared ownership with *this, if there are any, will report a use_count() that is one less than its previous value. One. Less. The count goes down, the friendship circle shrinks, it's very main character energy.
π NOTES π
- Unlike
std::unique_ptr, the deleter ofstd::shared_ptris invoked even if the managed pointer is null. Fr fr, it always calls the deleter. Not me being surprised by this either. π
π₯ EXAMPLE π₯
Run this code, trust me, it's a whole journey:
// Run this code
#include <iostream>
#include <memory>
struct S
{
S() { std::cout << "S::S()\n"; }
~S() { std::cout << "S::~S()\n"; }
struct Deleter
{
void operator()(S* s) const
{
std::cout << "S::Deleter()\n";
delete s;
}
};
};
int main()
{
auto sp = std::shared_ptr<S>{new S, S::Deleter{}};
auto use_count = [&sp](char c)
{
std::cout << c << ") use_count(): " << sp.use_count() << '\n';
};
use_count('A');
{
auto sp2 = sp;
use_count('B');
{
auto sp3 = sp;
use_count('C');
}
use_count('D');
}
use_count('E');
// sp.reset();
// use_count('F'); // would print "F) use_count(): 0"
}
β Output β
S::S()
A) use_count(): 1
B) use_count(): 2
C) use_count(): 3
D) use_count(): 2
E) use_count(): 1
S::Deleter()
S::~S()
the count goes 1 β 2 β 3 β 2 β 1 and then the deleter runs and THEN the destructor runs. ate. πβ¨
π SEE ALSO π
destructorβ destroys aweak_ptr(public member function ofstd::weak_ptr<T>) β the weak sibling gets its own little goodbye moment, we love to see it π§
k that's the page!! no cap, you now understand the destructor better than most people at your school π source: http://cppreference.com, version/date 2024.06.10 β that's the whole footer, we're mentioning it because it's cute and because it's literally on the page ππΈπ¦ periodt β¨π
π¦ 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