std::weak_ptr::swap(3)

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

πŸ¦‹ std::weak_ptr::swap β€” C++ Standard Libary, section 3 πŸ¦‹

okay so bestie, this is the std::weak_ptr::swap(3) page from the C++ Standard Libary manual, and it's a tiny little icon. no cap.

✨ NAME ✨

std::weak_ptr::swap β€” and yes, the name is literally std::weak_ptr::swap. it's giving β€œI contain multitudes, but the multitudes are the same name.” πŸ’…

🌸 Synopsis 🌸

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

This exchanges the stored pointer values and the ownerships of *this and r. Reference counts, if any, are not adjusted. 🚨

bestie, read that last bit again: reference counts, if any, are not adjusted. it's not doing a little count dance for you. πŸ™ˆ

πŸ’– Parameters πŸ’–

  • r β€” a smart pointer to exchange the contents with. that's the whole parameter. slay, simple. 🫢

⭐ Return value ⭐

The return value is (none) β€” literally nothing comes back. it's a void moment, periodt. 😌

πŸ¦‹ Example πŸ¦‹

here's the example, kept exact because we do not play with code in this house. run it and vibe-check the output:

// Run this code

#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> sp1 = std::make_shared<Foo>(100);
    std::shared_ptr<Foo> sp2 = std::make_shared<Foo>(200);
    std::weak_ptr<Foo> wp1 = sp1;
    std::weak_ptr<Foo> wp2 = sp2;
    auto print = [&]()
    {
        auto p1 = wp1.lock();
        auto p2 = wp2.lock();
        std::cout << " p1=" << (p1 ? p1->print() : "nullptr");
        std::cout << " p2=" << (p2 ? p2->print() : "nullptr") << '\n';
    };
    print();

    wp1.swap(wp2);
    print();

    wp1.reset();
    print();

    wp1.swap(wp2);
    print();
}

🌈 Output 🌈

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

source/version is http://cppreference.com, date is 2024.06.10. stay swapped, bestie πŸ’–βœ¨

πŸ“¦ where this page comes from