std::ostrea...buf_iterator(3)
π std::ostreambuf_iterator::ostreambuf_iterator β¨
okay so bestie, we're in the C++ Standard Library today β this is the constructor page for std::ostreambuf_iterator::ostreambuf_iterator, and honestly it's giving "short and iconic." π Building one of these iterators is literally how you get your write-on-sight iterator vibe going. Let's go. π¦
πΈ Synopsis πΈ
ostreambuf_iterator( streambuf_type* buffer ) (until C++11)
throw();
ostreambuf_iterator( streambuf_type* buffer ) (since C++11)
noexcept; (1)
ostreambuf_iterator( ostream_type& stream ) (until C++11)
throw(); (2)
ostreambuf_iterator( ostream_type& stream ) (since C++11)
noexcept;
So there's two flavors, no cap:
- Constructs the iterator with the private
streambuf_type*member set tobufferand thefailed()flag set tofalse. Heads up though β the behavior is undefined ifbufferis a null pointer. π Like fr fr, don't do that. - Same as
ostreambuf_iterator(stream.rdbuf()). That's it, that's the whole thing. π
π«Ά Parameters π«Ά
streamβ the output stream whoserdbuf()will be accessed by this iterator.bufferβ the output stream buffer to be accessed by this iterator.
π Example π
The page says // Run this code, so go off, queen π
#include <fstream>
#include <iostream>
#include <iterator>
int main()
{
const char* file = "test.txt";
{
std::basic_filebuf<char> f;
f.open(file, std::ios::out);
std::ostreambuf_iterator<char> out1(&f);
*out1 = 'a'; // writes to file via iterator
}
// read back from the file
char a;
std::cout << ((std::ifstream{file} >> a), a) << std::endl;
std::ostreambuf_iterator<wchar_t> out2{std::wcout};
*out2 = L'b';
}
β Output β
a
b
look at that, a then b, the assignment through the iterator literally just worked. observed. π
π Defect reports π
The following behavior-changing defect reports were applied retroactively to previously published C++ standards. retroactive glow-up, we love to see it β¨
LWG 112β applied to C++98. As published: the requirement "the argument cannot be null" was applied to overload (2). Correct behavior: applies to overload (1) instead. π (classic mix-up, lowkey embarrassing but they fixed it)P2325R3β applied to C++20. As published: default constructor was provided as iterators must bedefault_initializable. Correct behavior: C++20 removed the requirement. π«
ok that's the whole page!! every flag, every overload, every DR, all accounted for. no notes. π
β¨ that's a wrap, bestie β¨ β this little gem comes from http://cppreference.com, dated 2024.06.10, filed under the manual page std::ostrea...buf_iterator(3). go forth and construct your iterators responsibly (and never with a null pointer, i'm begging π«Άπ).
π¦ 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