Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::swap(std::optional)

      From cppreference.com
      <cpp‎ |utility‎ |optional
       
       
      Utilities library
       
       
      Defined in header<optional>
      template<class T>

      void swap(std::optional<T>& lhs,

                 std::optional<T>& rhs)noexcept(/* see below */);
      (since C++17)
      (constexpr since C++20)

      Overloads thestd::swap algorithm forstd::optional. Exchanges the state oflhs with that ofrhs. Effectively callslhs.swap(rhs).

      This overload participates in overload resolution only ifstd::is_move_constructible_v<T> andstd::is_swappable_v<T> are bothtrue.

      Contents

      [edit]Parameters

      lhs, rhs -optional objects whose states to swap

      [edit]Return value

      (none)

      [edit]Exceptions

      noexcept specification:  
      noexcept(noexcept(lhs.swap(rhs)))

      [edit]Notes

      Feature-test macroValueStdFeature
      __cpp_lib_optional202106L(C++20)
      (DR20)
      Fullyconstexpr

      [edit]Example

      Run this code
      #include <iostream>#include <optional>#include <string> int main(){std::optional<std::string> a{"██████"}, b{"▒▒▒▒▒▒"}; auto print=[&](autoconst& s){std::cout<< s<<"\t""a = "<< a.value_or("(null)")<<"  ""b = "<< b.value_or("(null)")<<'\n';};     print("Initially:");std::swap(a, b);    print("swap(a, b):");    a.reset();    print("\n""a.reset():");std::swap(a, b);    print("swap(a, b):");}

      Output:

      Initially:   a = ██████  b = ▒▒▒▒▒▒swap(a, b):  a = ▒▒▒▒▒▒  b = ██████ a.reset():   a = (null)  b = ██████swap(a, b):  a = ██████  b = (null)

      [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 the required operations can beconstexpr in C++20madeconstexpr

      [edit]See also

      exchanges the contents
      (public member function)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/utility/optional/swap2&oldid=172851"

      [8]ページ先頭

      ©2009-2025 Movatter.jp