std::basic_string::swap(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’– 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 if Allocator does not propagate on swap and (since C++11) the allocators of *this and other are 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 of std::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