std::basic_ofstream::swap(3)
π¦ 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 twobasic_filebufobjects (C++11) (public member function ofstd::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
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms