std::swap(s...c_ifstream)(3)

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

okay so bestie, welcome to std::swap(s...c_ifstream)(3) from the C++ Standard Libary (yes, that's literally how the manual spells it up top, and we respect the typo πŸ’…). It's giving very specific-helper-overload energy, and we're gonna get through every detail together. 🫢

🌸 NAME 🌸

std::swap(std::basic_ifstream) β€” std::swap(std::basic_ifstream) (the NAME line really said it twice, so we're keeping it twice, periodt ✨).


✨ Synopsis ✨

          template< class CharT, class Traits >
          void swap( basic_ifstream<CharT, Traits>& lhs, basic_ifstream<CharT,
       Traits>& rhs
          );

So this is the overload that specializes the std::swap algorithm for std::basic_ifstream. No cap, that's the whole point. It exchanges the state of lhs with that of rhs, and effectively calls lhs.swap(rhs). πŸ¦‹


🫢 Parameters 🫢

  • lhs, rhs β€” the streams whose state to swap. That's it, those are the two besties getting their states traded. πŸ’–

πŸ’– Return value πŸ’–

(none) β€” literally nothing comes back. No return value, no drama, just vibes. πŸŽ€


😭 Exceptions 😭

May throw implementation-defined exceptions. So like, the implementation gets to decide the exception details β€” that's the caveat, fr fr. πŸ’€


🧚 Example 🧚

This example is iconic, and yes, the // Run this code line is part of the package:

        // Run this code

        #include <fstream>
        #include <iostream>
        #include <string>

        bool create_stream(std::ifstream& fs)
        {
            try
            {
                std::string some_name = "/tmp/test_file.txt";
                std::ios_base::openmode some_flags = fs.trunc; // | other flags

                if (std::ifstream ts{some_name, some_flags}; ts.is_open())
                {
                    std::swap(ts, fs); // stream objects are not copyable =>
       swap
                    return true;
                }
            }
            catch (...)
            {
                std::cout << "Exception!\n";
            }
            return false;
        }

        int main()
        {
            if (std::ifstream fs; create_stream(fs))
            {
                // use fs stream
            }
        }

The comment says stream objects are not copyable, so swap is the move β€” and that's the whole demo. 🧚✨


πŸ‘‘ See also πŸ‘‘

  • swap β€” swaps two file streams (C++11) (public member function) 🌈

πŸ’Œ okay that's the page, bestie. It came from http://cppreference.com, dated 2024.06.10, and it's the std::swap(s...c_ifstream)(3) manual page. Byeee, slay responsibly. πŸ«ΆπŸ’…
πŸ“¦ where this page comes from