0

为什么这么多人在这样的情况下对 std::ostringstream 对象使用 flush() 成员函数:

#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;
}

没有此调用的输出将是相同的。

所以为什么?我什么时候应该使用 flush() 成员函数?

4

1 回答 1

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.

于 2012-10-21T20:30:36.560 回答