5

Can someone explain the subtle difference in:

ofstream f("test.txt")
std::stringstream s;
s<<"";
f << s.rdbuf();
f.good() // filestream is bad!!


ofstream f("test.txt")
std::stringstream s;
s<<"";
f << s.str();
f.good() // is still ok!

I mostly use .rdbuf() to push the stringstream to the file (because its more efficient), but if the stringstream is empty than the filestream gets bad...? Isnt this stupid? I think I dont quite understand << s.rdbuf() ...

Gabriel
  • 7,477
  • 5
  • 47
  • 87

1 Answers1

6

The insertion operator that "inserts" streambuffers sets the failbit if no characters could be extracted from the streambuffer - [ostream.inserters]/9:

If the function inserts no characters, it calls setstate(failbit) (which may throw ios_base:: failure (27.5.5.4)).

Whereas the insertion operator that outputs a string obviously doesn't consider the amount of characters written.

It seems that this is because inserting a streambuffer "forwards" the streambuffer into the stream - if no characters could be extracted most certainly there was an error in the streambuffer itself and this error should be represented by the streams error state. Outputting an empty stream is an exception that was presumably not considered important enough to take into account when this rule was created.

Columbo
  • 57,033
  • 7
  • 145
  • 194