std::shared...~shared_ptr(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’– 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 of std::shared_ptr is 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 a weak_ptr (public member function of std::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