std::swap(std::weak_ptr)(3)

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

πŸ’– std::swap(std::weak_ptr) πŸ’–

okay bestie, welcome to the C++ Standard Libary manual page for std::swap(std::weak_ptr) β€” yes, that’s the whole name, and yes, it’s a mouthful. no cap. This is the group-chat explanation, but every fact is staying exactly where it belongs. ✨


πŸŽ€ NAME πŸŽ€

std::swap(std::weak_ptr) β€” literally the page for std::swap(std::weak_ptr). It’s giving β€œspecialized swap for weak pointers” energy. πŸ’…


🌸 Synopsis 🌸

Defined in header <memory>
template< class T >
(since C++11)
void swap( std::weak_ptr<T>& lhs, std::weak_ptr<T>& rhs ) noexcept;

This thing specializes the std::swap algorithm for std::weak_ptr. It swaps the contents of lhs and rhs, and it calls lhs.swap(rhs). 🫢


πŸ¦‹ Parameters πŸ¦‹

  • lhs, rhs β€” smart pointers whose contents to swap ✨

πŸŽ€ Return value πŸŽ€

(none) β€” literally nothing comes back, bestie. It just does the swap. πŸ™ˆ


⭐ Complexity ⭐

Constant. no notes. just constant. πŸ”₯


πŸ’» Example πŸ’»

// 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();

    std::swap(wp1, wp2);
    print();

    wp1.reset();
    print();

    std::swap(wp1, wp2);
    print();
}

🌈 Output 🌈

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

πŸ‘€ See also πŸ‘€

  • swap β€” swaps the values of two objects (function template)
  • swap β€” swaps the contents (public member function)

mwah πŸ’‹ this cutie came from http://cppreference.com, dated 2024.06.10 β€” C++ Standard Libary manual, periodt. 🫢

πŸ“¦ where this page comes from