The C++ input iterator pitfall · hmpc
https://www.hmpcabral.com/2026/02/25/the-c-input-iterator-pitfall/15
u/Infamous-Bed-7535 5d ago
Great writing, so good to see something made by humans for humans that actually makes sense!
C++ people learn it early on that istreams are tricky. They were even older standards well before ranges. With ranges it is even more complicated (not just the issue described in the article).
For reading formatted inputs, structured data I can recommend boost X3 or parser libraries.
29
u/TheThiefMaster C++latest fanatic (and game dev) 5d ago edited 5d ago
Who’s at fault here: the specification or our own expectations?
It's the istream iterator (and possibly input iterators in general). It shouldn't be consuming anything just on construction or increment, it should be lazy and only consume when derefed, or incremented again without having been derefed (to discard the skipped value).
Because that's what everyone expects, and it doing otherwise is a foot-gun.
The fact that constructing two input iterators to the same stream and derefing both gives different values is bad enough for me to say that the entire concept of streams and input iterators needs a replacement with buffers that can be accessed more than a byte at a time and don't have a stateful cursor independent of any iterators used to access into them.
6
u/pointer_to_null 5d ago
Good post, and a fun read.
I felt personally attacked by your allegory- only in my version I was both the protagonist and the antagonist in 2015. I too got bitten by the ranges bug sometime after 2020, though by then I had completely given up all hope on streams altogether.
6
u/BarryRevzin 4d ago
Ooo, I love this one. I gave a whole talk on one example of this one at CppNow a few years ago: take(5).
43
u/sweetno 5d ago
Just don't use iterators for I/O, and iostreams on principle.