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

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

πŸŽ€ NAME πŸŽ€

okay so bestie, welcome to std::swap(s...sic_fstream)(3) from the C++ Standard Libary manual πŸ’… β€” manual name folded in, spelling kept exactly how it showed up 🫢.

The name is literally:

std::swap(std::basic_fstream) - std::swap(std::basic_fstream)

✨ Synopsis ✨

Here's the signature, no cap:

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

So what's the tea? It's the specialization of the std::swap algorithm for std::basic_fstream. It exchanges the state of lhs with that of rhs, and it effectively calls lhs.swap(rhs) β€” iconic behavior, honestly 🌟.

🌸 Parameters 🌸

  • lhs, rhs β€” streams whose state to swap. That's the whole parameter list, bestie 🫢.

🫢 Return value 🫢

(none) β€” literally nothing comes back. The return value is (none), and we respect that 😌.

😭 Exceptions 😭

May throw implementation-defined exceptions. That's the caveat, and it's staying right here πŸ’€.

πŸ¦‹ Example πŸ¦‹

Run this code, bestie β€” here's the whole sample:

// Run this code

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

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

        if (std::fstream 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::fstream fs; create_stream(fs))
    {
        // use fs stream
    }
}

πŸ‘‘ See also πŸ‘‘

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

source/version check: this page came from http://cppreference.com, dated 2024.06.10, for std::swap(s...sic_fstream)(3) β€” byeee, go swap your streams, mwah πŸ’–

πŸ“¦ where this page comes from