std::variant::swap(3)
π 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
*thisandrhsare valueless by exception, does nothing. - Otherwise, if both
*thisandrhshold the same alternative, callsswap(*std::get_if<i>(this), *std::get_if<i>(std::addressof(rhs)))whereiisindex(). If an exception is thrown, the state of the values depends on the exception safety of theswapfunction called. - Otherwise, exchanges values of
rhsand*this. If an exception is thrown, the state of*thisandrhsdepends on exception safety ofvariant's move constructor.
π¨ The behavior is undefined unless lvalues of typeT_iareSwappableandstd::is_move_constructible_v<T_i>is true for allT_iinTypes....β 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 byswap(*std::get_if<i>(this), *std::get_if<i>(std::addressof(rhs)))withibeingindex(). - Otherwise, may throw any exception thrown by the move constructors of the alternatives currently held by
*thisandrhs.
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:swapwas notconstexprwhile the required operations can beconstexprin C++20. Correct behavior: madeconstexpr.
β 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
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms