std::swap(s...c_ifstream)(3)
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 fromhttp://cppreference.com, dated2024.06.10, and it's thestd::swap(s...c_ifstream)(3)manual page. Byeee, slay responsibly. π«Άπ
π¦ 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