From cppreference.com
voidswap(basic_string&other);(until C++17)voidswap(basic_string&other)noexcept(/* see below */);(since C++17)
(constexpr since C++20)Exchanges the contents of the string with those of other. All iterators and references may be invalidated.
If std::allocator_traits<allocator_type>::propagate_on_container_swap::value is true, then the allocators are exchanged using an unqualified call to non-member swap. Otherwise, they are not swapped (and if get_allocator()!=other.get_allocator(), the behavior is undefined).
(since C++11)Parameters
other - string to exchange the contents with Complexity
Constant.
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)
specification:
noexcept(std::allocator_traits<Allocator>::propagate_on_container_swap::value||std::allocator_traits<Allocator>::is_always_equal::value)(since C++17)Example
Run this code
#include<iostream>#include<string>intmain(){std::stringa="AAA";std::stringb="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 = AAA b = BBBB After swap: a = BBBB b = AAA Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
DR Applied to Behavior as published Correct behavior
C++98 swap() might throw an exception no exception is thrown
C++98 swapping strings did not preserve the character orders orders are also preserved
(
) C++11 no exception was thrown in the case
of unequal non-propagating allocators the behavior is
undefined in this case See also
swaps the values of two objects
(function template)
swaps two ranges of elements
(function template & algorithm function object)
(C++20)
swaps the contents
(public member function of std::basic_string_view<CharT,Traits>)