Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::basic_string<CharT,Traits,Allocator>::swap

      From cppreference.com
      <cpp‎ |string‎ |basic string
       
       
       
      std::basic_string
       
      void swap( basic_string& other);
      (until C++17)
      void swap( basic_string& other)noexcept(/* see below */);
      (since C++17)
      (constexpr since C++20)

      Exchanges the contents of the string with those ofother. All iterators and references may be invalidated.

      Ifstd::allocator_traits<allocator_type>::propagate_on_container_swap::value istrue, then the allocators are exchanged using an unqualified call to non-memberswap. Otherwise, they are not swapped (and ifget_allocator()!= other.get_allocator(), the behavior is undefined).

      (since C++11)

      Contents

      [edit]Parameters

      other - string to exchange the contents with

      [edit]Complexity

      Constant.

      [edit]Exceptions

      No exception is thrown.

      (until C++11)

      No exception is thrown, unless the behavior is undefined.

      If an exception is thrown for any reason, this function has no effect (strong exception safety guarantee).

      (since C++11)


      noexcept specification:  
      noexcept(std::allocator_traits<Allocator>::propagate_on_container_swap::value||
               std::allocator_traits<Allocator>::is_always_equal::value)
      (since C++17)

      [edit]Example

      Run this code
      #include <iostream>#include <string> int main(){std::string a="AAA";std::string b="BBBB"; std::cout<<"Before swap:\n""a = "<< a<<"\n""b = "<< b<<"\n\n";     a.swap(b); std::cout<<"After swap:\n""a = "<< a<<"\n""b = "<< b<<'\n';}

      Output:

      Before swap:a = AAAb = BBBB After swap:a = BBBBb = AAA

      [edit]Defect reports

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

      DRApplied toBehavior as publishedCorrect behavior
      LWG 403C++98swap() might throw an exceptionno exception is thrown
      LWG 535C++98swapping strings did not preserve the character ordersorders are also preserved
      LWG 2151
      (P1148R0)
      C++11no exception was thrown in the case
      of unequal non-propagating allocators
      the behavior is
      undefined in this case

      [edit]See also

      swaps the values of two objects
      (function template)[edit]
      swaps two ranges of elements
      (function template)[edit]
      swaps the contents
      (public member function ofstd::basic_string_view<CharT,Traits>)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/string/basic_string/swap&oldid=182493"

      [8]ページ先頭

      ©2009-2025 Movatter.jp