Namespaces
Variants
Views
Actions

std::variant<Types...>::swap

From cppreference.com
< cpp‎ | utility‎ | variant
 
 
Utilities library
General utilities
Date and time
Function objects
Formatting library (C++20)
(C++11)
Relational operators (deprecated in C++20)
Integer comparison functions
(C++20)
Swap and type operations
(C++14)
(C++11)

(C++11)
(C++11)
(C++17)
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++17)

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

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<i>(*this), std:get<i>(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....

Contents

[edit] Parameters

rhs - a variant object to swap with

[edit] Return value

(none)

[edit] 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>) && ...))

[edit] Example

#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