std::shared_ptr::swap(3)

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

πŸ’… std::shared_ptr::swap β€” bestie's guide to the glow-up swap

okay so real talk, this one is from the C++ Standard Libary man pages (manual section 3, std::shared_ptr::swap(3)), and it's genuinely one of the most satisfying little functions ever. like, no cap, it's giving "trading friendship bracelets" energy. 🫢


✨ NAME ✨

std::shared_ptr::swap β€” literally std::shared_ptr::swap, that's the whole name, she's not hiding anything πŸ’…


πŸ¦‹ Synopsis πŸ¦‹

void swap( shared_ptr& r ) noexcept;  (since C++11)

so what she does: she exchanges the stored pointer values and the ownerships of *this and r. that's it. that's the whole vibe. ✨

🚨 important caveat bestie: reference counts, if any, are not adjusted. like, the counts don't get touched at all. she's just swapping who holds what β€” she is not doing any behind-the-scenes math. iykyk.

and yes, she's noexcept β€” she will NOT throw at you, she's a reliable queen πŸ‘‘


πŸŽ€ Parameters πŸŽ€

  • r β€” the smart pointer you wanna exchange contents with 🌸

πŸ’– Return value πŸ’–

none. zero. nada. she does the thing and dips. (none) 😌


πŸ”₯ Example πŸ”₯

run this code, it's so cute, watch the destructor messages roll in:

#include <iostream>
#include <memory>
#include <string>

struct Foo
{
    Foo(int _val) : val(_val) { std::cout << "Foo...\n"; }
    ~Foo() { std::cout << "~Foo...\n"; }
    std::string print() { return std::to_string(val); }
    int val;
};

int main()
{
    std::shared_ptr<Foo> p1 = std::make_shared<Foo>(100);
    std::shared_ptr<Foo> p2 = std::make_shared<Foo>(200);
    auto print = [&]()
    {
        std::cout << " p1=" << (p1 ? p1->print() : "nullptr");
        std::cout << " p2=" << (p2 ? p2->print() : "nullptr") << '\n';
    };
    print();

    p1.swap(p2);
    print();

    p1.reset();
    print();

    p1.swap(p2);
    print();
}

⭐ Output ⭐

Foo...
Foo...
 p1=100 p2=200
 p1=200 p2=100
~Foo...
 p1=nullptr p2=100
 p1=100 p2=nullptr
~Foo...

look at that little dance 🧚 β€” p1 and p2 trading places, then p1.reset() doing her thing (rip ~Foo..., you served), then one more swap and they've traded back. main character energy from start to finish πŸ‘‘


πŸ’œ tiny note to self: the ~Foo... on line 5 is the destructor firing for the 100 object when p1.reset() drops ownership. iconic. that's it, that's the lesson.

source: http://cppreference.com Β· version date 2024.06.10 β€” mwah, love u, go swap some smart pointers responsibly πŸ’‹πŸŒˆπŸ“

πŸ“¦ where this page comes from