std::basic_ostream::swap(3)

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

πŸ’– NAME πŸ’–

Hey bestie πŸ’– welcome to the std::basic_ostream::swap(3) page from the C++ Standard Libary manual. The NAME section is giving exactly this and nothing else: std::basic_ostream::swap - std::basic_ostream::swap πŸ’…


✨ Synopsis ✨

Okay so here’s the protected king behavior, since C++11 ✨:

          protected:                        (since C++11)
          void swap( basic_ostream& rhs );

It calls basic_ios::swap(rhs) to swap all data members of the base class, except for rdbuf(), between *this and rhs πŸ‘‘ This swap function is protected: it is called by the swap functions of the swappable output stream classes std::basic_ofstream and std::basic_ostringstream, which know how to correctly swap the associated streambuffers. Periodt 🫢

Bestie, this swap is protected here. That means std::cout.swap(s2); is an ERROR: swap is a protected member β€” literally in the example comment. No cap πŸ’€

πŸŽ€ Parameters πŸŽ€

  • rhs β€” a basic_ostream of the same type to swap with πŸ¦‹

πŸ’… Example πŸ’…

The original has a lil // Run this code note right up top, and here’s the code exactly, bestie:

        #include <iostream>
        #include <sstream>
        #include <utility>

        int main()
        {
            std::ostringstream s1("hello");
            std::ostringstream s2("bye");

            s1.swap(s2); // OK, ostringstream has a public swap()
            std::swap(s1, s2); // OK, calls s1.swap(s2)

        //  std::cout.swap(s2); // ERROR: swap is a protected member

            std::cout << s1.str() << '\n';
        }

πŸ“ Output πŸ“

And the output is literally:

hello

Mwah πŸ’‹ this is the std::basic_ostream::swap(3) page, source/version http://cppreference.com, date 2024.06.10 β€” footer details delivered, bestie, not a drill 🫢🌈

πŸ“¦ where this page comes from