|
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
void swap( variant& rhs)noexcept(/* see below */); | (since C++17) (constexpr since C++20) | |
Swaps twovariant objects.
index(). If an exception is thrown, the state of the values depends on the exception safety of theswap function called.The program is ill-formed unless typeT_i areSwappable andstd::is_move_constructible_v<T_i> istrue for allT_i inTypes....
Contents |
| rhs | - | avariant object to swap with |
(none)
Ifthis->index()== rhs.index(), may throw any exception thrown byswap(*std::get_if<i>(this),*std::get_if<i>(std::addressof(rhs))) withi beingindex().
Otherwise, may throw any exception thrown by the move constructors of the alternatives currently held by*this andrhs.
| Feature-test macro | Value | Std | Feature |
|---|---|---|---|
__cpp_lib_variant | 202106L | (C++20) (DR) | Fullyconstexprstd::variant |
#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 abcabc 2
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
|---|---|---|---|
| P2231R1 | C++20 | swap was notconstexpr while non-trivial destructors can beconstexpr in C++20 | madeconstexpr |
(C++17) | specializes thestd::swap algorithm (function template)[edit] |