std::basic_ofstream::swap(3)

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

πŸ¦‹ std::basic_ofstream::swap(3) β€” the C++ Standard Libary glow-up πŸ¦‹

okay bestie, so this is a page straight out of the C++ Standard Libary (yes that's how it's spelled on the page, keep it πŸ’…), and it's all about std::basic_ofstream::swap. That's the whole name, that's the whole vibe β€” the page literally just says std::basic_ofstream::swap - std::basic_ofstream::swap under NAME and honestly? iconic. minimal. she said "the name is the name." πŸŽ€


✨ SYNOPSIS ✨

void swap( basic_ofstream& other );  (since C++11)

Exchanges the state of the stream with those of other. 🫢

So how does she actually do it? Under the hood it's a two-step slay πŸ”₯ β€” it calls basic_ostream<CharT, Traits>::swap(other) and it calls rdbuf()->swap(other.rdbuf()). That's it, that's the whole move. no cap.


🌸 PARAMETERS 🌸

  • other β€” the stream you're exchanging state with. your swap partner. your other half 🫢

πŸ’œ RETURN VALUE πŸ’œ

(none) β€” she gives you nothing back, and that's fine, she's not that kind of function πŸ’…


πŸ“ EXCEPTIONS πŸ“

May throw implementation-defined exceptions. 😭 so like, whatever your implementation decides to throw, that's on her β€” it's not specified here, fr fr.


🌈 EXAMPLE 🌈

the page says // Run this code right here, so go run it bestie 🧚

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

bool create_stream(std::fstream& fs, const std::string& path)
{
    try
    {
        std::fstream ts{path, ts.trunc | ts.in | ts.out};
        if (ts.is_open())
        {
            ts.swap(fs); // stream objects are not copyable
            return true;
        }
    }
    catch (...)
    {
        std::cout << "Exception!\n";
    }
    return false;
}

void use_stream(std::fstream& fs)
{
    fs.seekg(0);
    std::string data;
    fs >> data;
    std::cout << "data: " << std::quoted(data) << '\n';
}

int main()
{
    std::fstream fs;
    std::string path = "/tmp/test_file.txt";
    if (create_stream(fs, path))
    {
        fs.write(path.c_str(), path.length());
        use_stream(fs);
    }
}
lowkey obsessed with the comment // stream objects are not copyable β€” the example is out here reminding you that swapping is the whole reason she exists 😭 stream objects can't be copied, so swap is the main character energy move πŸ‘‘

⭐ POSSIBLE OUTPUT ⭐

data: "/tmp/test_file.txt"

look at that. ate. πŸ’…βœ¨


πŸ‘‘ SEE ALSO πŸ‘‘

  • operator= β€” moves the file stream (C++11) (public member function)
  • swap β€” swaps two basic_filebuf objects (C++11) (public member function of std::basic_filebuf<CharT,Traits>)

iykyk, these two are her besties 🌸


okay that's the whole page β€” no notes, she's perfect πŸ’– and before you go: this lil masterpiece lives over at http://cppreference.com, dated 2024.06.10, filed under std::basic_ofstream::swap(3). mwah πŸ’‹ go swap something πŸ¦‹

πŸ“¦ where this page comes from