std::basic_filebuf::swap(3)

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

✨ std::basic_filebuf::swap(3) ✨

Okay so we're in the C++ Standard Libary β€” that's the manual name, bestie β€” and today's main character is std::basic_filebuf::swap. πŸ’– This page is all about swapping the state and contents of two file buffers, and it's giving very specific C++ energy.

🌸 NAME 🌸

std::basic_filebuf::swap - std::basic_filebuf::swap. Yes, the NAME section is just the name twice; iconic. ✨

πŸ’… Synopsis πŸ’…

void swap( std::basic_filebuf& rhs );  (since C++11)

Swaps the state and the contents of *this and rhs. No cap, that's the whole move. πŸ”₯

πŸŽ€ Parameters πŸŽ€

  • rhs β€” another basic_filebuf. That's the one parameter, bestie. 🫢

πŸ¦‹ Return value πŸ¦‹

(none) β€” no return value here. It's void, so don't go looking for a return gift. πŸ’€

🌈 Notes 🌈

This function is called automatically when swapping std::fstream objects, so the stream machinery handles it for you. Because of that, the page says it is rarely necessary to call it directly. Lowkey a background character, highkey still important. πŸ‘‘

πŸ“ Example πŸ“

The original says // Run this code β€” here's the whole thing, exactly as the page gives it:

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

int main()
{
    std::ifstream fin("test.in"); // read-only
    std::ofstream fout("test.out"); // write-only

    std::string s;
    getline(fin, s);
    std::cout << s << '\n'; // outputs the first line of test.in

    fin.rdbuf()->swap(*fout.rdbuf()); //swap the underlying buffers

    getline(fin, s); // fails: cannot read from a write-only filebuf
    std::cout << s << '\n'; // prints empty line
}

Vibe check on the example: fin is read-only, fout is write-only, and after the underlying buffers get swapped, trying to getline from fin fails because now it's basically trying to read from a write-only filebuf. The output is an empty line. 😭

πŸ‘‘ See also πŸ‘‘

  • operator= β€” assigns a basic_filebuf object. (C++11) (public member function)
  • std::swap(std::basic_filebuf) β€” specializes the std::swap algorithm. (C++11) (function template)
  • swap β€” swaps two file streams. (C++11) (public member function of std::basic_fstream<CharT,Traits>)

Source/version/date sign-off, bestie: this page came from http://cppreference.com, dated 2024.06.10, and it's the std::basic_filebuf::swap(3) manual page. Bye! πŸ’œ

πŸ“¦ where this page comes from