SysTutorials

Linux Manual Pages › Section 3

stdvariantswap(3)

std::variant<Types…>::swap - std::variant<Types…>::swap

Synopsis

void swap(variant &rhs) noexcept(/* see below */);
(1)(since C++ 17)

Swaps two variant objects.

Parameters

rhs - a variant object to swap with

Return value

(none)

Exceptions

If this->index() == rhs.index(), may throw any exception thrown by swap(std::get<i>(*this), std::get<i>(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 <variant>
#include <string>
#include <iostream>
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