std::swap(std::unique_ptr)(3)

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

πŸ’– std::swap(std::unique_ptr)(3) πŸ’–

Okay bestie, this is the std::swap(std::unique_ptr) page from the C++ Standard Libary manual (yes, β€œLibary” is literally how the header spells it β€” we don’t fix, we preserve πŸ’…). Buckle up.

🌸 NAME 🌸

std::swap(std::unique_ptr) β€” aka std::swap(std::unique_ptr). That’s the name, that’s the whole name, no cap. πŸŽ€

✨ Synopsis ✨

The original synopsis is formatted a little feral, so here it is exactly:

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

Translation: this specializes the std::swap algorithm for std::unique_ptr. It swaps the contents of lhs and rhs. And how does it do it? It calls lhs.swap(rhs). Slay. ✨

🚨 Vibe check: this function does not participate in overload resolution unless std::is_swappable_v<D> is true (since C++17). That’s important, bestie β€” don’t skip it.

πŸŽ€ Parameters πŸŽ€

  • lhs, rhs β€” the smart pointers whose contents are getting swapped. 🫢

πŸ’œ Return value πŸ’œ

None. Literally (none). It’s giving void energy, and honestly that’s the point. πŸ’€

⭐ Complexity ⭐

Constant. That’s it, that’s the complexity. No cap. ⭐

πŸ¦‹ Example πŸ¦‹

// Run this code β€” yes, that’s literally what the page says, so run it, bestie:

#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::unique_ptr<Foo> p1 = std::make_unique<Foo>(100);
    std::unique_ptr<Foo> p2 = std::make_unique<Foo>(200);
    auto print = [&]() {
        std::cout << " p1=" << (p1 ? p1->print() : "nullptr");
        std::cout << " p2=" << (p2 ? p2->print() : "nullptr") << '\n';
    };
    print();

    std::swap(p1, p2);
    print();

    p1.reset();
    print();

    std::swap(p1, p2);
    print();
}

πŸ”₯ Output πŸ”₯

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

🌈 See also 🌈

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

So that’s the whole page, bestie. Source: http://cppreference.com; date: 2024.06.10; manual page: std::swap(std::unique_ptr)(3). Mwah πŸ’‹πŸ’–

πŸ“¦ where this page comes from