0

Why so many people use flush() member function for std::ostringstream objects in situations like this:

#include <iostream>
#include <sstream>

int main()
{
   float f = 12.345f / 100;
   std::ostringstream ios;
   ios << f;
   ios.flush();
   std::cout << f << " : " << ios.str() << std::endl;
}

Output without this call will be the same.

So, why? And when should i use flush() member function?

Reunanen
  • 7,921
  • 2
  • 35
  • 57
FrozenHeart
  • 19,844
  • 33
  • 126
  • 242
  • Good question. It probably makes sense in generic contexts where you cannot really be sure about the type of stream and it prevents breakage should someone ever change the code to a different stream. The performance penalty here is minimal. – pmr Oct 21 '12 at 20:33

1 Answers1

2

There is no good reason to use flush in that situation. I'd be interested to know where these so many people are. Personally I can't recall ever seeing flush used like that.

Most of the time I would put code like that down to superstition. Someone had a bug, which they never understood, but they tried flush and mysteriously the bug went away. Using flush wasn't the real reason the bug went away but it's use stuck.

You should use flush on a buffered stream when you want to buffered data to be output immediately.

john
  • 85,011
  • 4
  • 57
  • 81