std::basic_...sic_ostream(3)

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

🌈 NAME 🌈

std::basic_ostream::~basic_ostream β€” literally the destructor of std::basic_ostream, and yes bestie the name is the whole name, we're not doing subtitles today πŸ’…

This page lives in the C++ Standard Library manual, section 3, and it's here to walk you through exactly what this little destructor does (and, iconic behaviour, what it doesn't do) 🫢


✨ SYNOPSIS ✨

virtual ~basic_ostream();

Okay so boom β€” this destroys the basic_ostream object. That's it. That's the whole job πŸ’€

But here's the part everyone gets wrong, so listen up: this destructor does not perform any operation on the underlying streambuffer (rdbuf()). Like, none. Zero. She's not touching it, no cap πŸ™ˆ

So who cleans up the buffer? The destructors of the derived output streams, bestie β€” think std::basic_ofstream and std::basic_ostringstream. Those are the ones responsible for calling the destructors of the stream buffers. They hold it down, periodt πŸ‘‘

Fr fr, don't expect basic_ostream's destructor to babysit your streambuf. It simply does not. That is not her main character energy 🌸

πŸŽ€ EXAMPLE πŸŽ€

Run this code, it's a whole vibe πŸ”₯

// Run this code

#include <iostream>
#include <sstream>

void add_words(std::streambuf* p)
{
    std::ostream buf(p); // buf shares the buffer with s
    buf << " is the answer";
} // calls the destructor of buf. p remains unaffected

int main()
{
    std::ostringstream s;
    s << 42;
    add_words(s.rdbuf());
    s << ".";
    std::cout << s.str() << '\n';
}

Notice that little comment, because it's the whole point πŸ‘€ β€” buf shares the buffer with s, and when buf's destructor runs, p remains unaffected. The buffer survives. Slay πŸ¦‹


πŸ’– OUTPUT πŸ’–

42 is the answer.

Ate and left no crumbs, honestly πŸ“


And that's the tea, bestie β˜• β€” this page is straight from http://cppreference.com, dated 2024.06.10, and it answers to the name std::basic_...sic_ostream(3) (the title's a little shy, we love that for her) πŸ’œβœ¨

πŸ“¦ where this page comes from