std::basic_string::swap(3)
π NAME π
std::basic_string::swap β std::basic_string::swap (yes bestie, it's self-titled, main character energy only π
). This page is from the C++ Standard Libary (that spelling is literally what the source says, leave it alone π), and it's the std::basic_string::swap(3) manual page.
π Synopsis β¨
void swap( basic_string& other ); (until C++17)
void swap( basic_string& other ) noexcept(/* see below */); (since C++17)
(constexpr since C++20)
It exchanges the contents of the string with those of other. All iterators and references may be invalidated. π«
π¨ undefined behavior alert: the behavior is undefined ifAllocatordoes not propagate on swap and (since C++11) the allocators of*thisandotherare unequal. Not a vibe. π
π§΅ Parameters π§΅
otherβ string to exchange the contents with.
π Return value π
(none)
β‘ Complexity β‘
Constant. No cap. π
π Exceptions π
- Until C++11: No exception is thrown.
- Since C++11: exceptions can only be thrown in the case where the behavior is undefined (see above).
If an exception is thrown for any reason, this function has no effect (strong exception safety guarantee). Iconic behavior, honestly. β¨
noexcept specification (since C++17):
noexcept(std::allocator_traits<Allocator>::propagate_on_container_swap::value ||
std::allocator_traits<Allocator>::is_always_equal::value)
π§ͺ 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 = 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.
LWG 403β applied to C++98: behavior as published was βswap()might throw an exceptionβ; correct behavior is βno exception is thrownβ.LWG 535β applied to C++98: behavior as published was βswapping strings did not preserve the character ordersβ; correct behavior is βorders are also preservedβ.
π See also π
swapβ swaps the values of two objects (function template).swap_rangesβ swaps two ranges of elements (function template).swapβ swaps the contents (public member function ofstd::basic_string_view<CharT,Traits>).
π·οΈ Category π·οΈ
conditionally noexcept
okay bye bestie π«Ά this page came from http://cppreference.com, dated 2024.06.10, and the footerβs page label was std::basic_string::swap(3) πβ¨
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms