Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

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

      From cppreference.com
      <cpp‎ |utility‎ |variant
       
       
      Utilities library
       
       
      void swap( variant& rhs)noexcept(/* see below */);
      (since C++17)
      (constexpr since C++20)

      Swaps twovariant objects.

      • If both*this andrhs are valueless by exception, does nothing.
      • Otherwise, if both*this andrhs hold the same alternative, callsswap(*std::get_if<i>(this),*std::get_if<i>(std::addressof(rhs))) wherei isindex(). If an exception is thrown, the state of the values depends on the exception safety of theswap function called.
      • Otherwise, exchanges values ofrhs and*this. If an exception is thrown, the state of*this andrhs depends on exception safety of variant's move constructor.

      The program is ill-formed unless typeT_i areSwappable andstd::is_move_constructible_v<T_i> istrue for allT_i inTypes....

      Contents

      [edit]Parameters

      rhs - avariant object to swap with

      [edit]Return value

      (none)

      [edit]Exceptions

      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.

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

      [edit]Notes

      Feature-test macroValueStdFeature
      __cpp_lib_variant202106L(C++20)
      (DR)
      Fullyconstexprstd::variant

      [edit]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 abcabc 2

      [edit]Defect reports

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

      DRApplied toBehavior as publishedCorrect behavior
      P2231R1C++20swap was notconstexpr while non-trivial destructors can beconstexpr in C++20madeconstexpr

      [edit]See also

      specializes thestd::swap algorithm
      (function template)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/utility/variant/swap&oldid=178523"

      [8]ページ先頭

      ©2009-2025 Movatter.jp