std::variant::swap(3)

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

πŸ’– NAME πŸ’–

okay so this is std::variant::swap - std::variant::swap (yes bestie, the name is literally the same twice, iconic πŸ’…). It’s the std::variant::swap(3) page from the C++ Standard Libary manual β€” and yes, that’s how the manual spells β€œLibary,” no cap 🫢.


✨ Synopsis ✨

std::variant::swap swaps two variant objects. Here’s the signature situation:

void swap( variant& rhs ) noexcept(/* see below */);

since C++17 until C++20

constexpr void swap( variant& rhs ) noexcept(/* see below */);

since C++20

Swaps two variant objects.

  • If both *this and rhs are valueless by exception, does nothing.
  • Otherwise, if both *this and rhs hold the same alternative, calls swap(*std::get_if<i>(this), *std::get_if<i>(std::addressof(rhs))) where i is index(). If an exception is thrown, the state of the values depends on the exception safety of the swap function called.
  • Otherwise, exchanges values of rhs and *this. If an exception is thrown, the state of *this and rhs depends on exception safety of variant's move constructor.
🚨 The behavior is undefined unless lvalues of type T_i are Swappable and std::is_move_constructible_v<T_i> is true for all T_i in Types.... β€” undefined behavior is not a vibe, bestie, so respect it.

πŸŽ€ Parameters πŸŽ€

  • rhs β€” a variant object to swap with.

🌸 Return value 🌸

(none) β€” literally nothing comes back, bestie. 🫢

πŸ’… Exceptions πŸ’…

  • If this->index() == rhs.index(), may throw any exception thrown by swap(*std::get_if<i>(this), *std::get_if<i>(std::addressof(rhs))) with i being index().
  • Otherwise, may throw any exception thrown by the move constructors of the alternatives currently held by *this and rhs.

noexcept specification:

noexcept(((std::is_nothrow_move_constructible_v<Types> &&
                     std::is_nothrow_swappable_v<Types>) && ...))

πŸ¦‹ Example πŸ¦‹

// Run this code

#include <iostream>
#include <string>
#include <variant>

int main()
{
    std::variant<int, std::string> v1{2}, v2{"abc"};
    std::visit([](auto&& x) { std::cout << x << ' '; }, v1);
    std::visit([](auto&& x) { std::cout << x << '\n'; }, v2);
    v1.swap(v2);
    std::visit([](auto&& x) { std::cout << x << ' '; }, v1);
    std::visit([](auto&& x) { std::cout << x << '\n'; }, v2);
}

🌈 Output 🌈

2 abc
abc 2

πŸ‘‘ Defect reports πŸ‘‘

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

  • P2231R1 β€” applied to C++20. Behavior as published: swap was not constexpr while the required operations can be constexpr in C++20. Correct behavior: made constexpr.

⭐ Category ⭐

  • conditionally noexcept

okay that’s the whole page, bestie 🫢 source: http://cppreference.com Β· version/date: 2024.06.10 Β· and yep, it’s the std::variant::swap(3) page. slay πŸ’…βœ¨

πŸ“¦ where this page comes from