In simple terms, what is the purpose of flush() in ostream

后端 未结 2 1101
余生分开走
余生分开走 2021-01-05 22:40

By definition taken from: http://www.cplusplus.com/reference/iostream/ostream/flush/ , it is not clear why the function exists, and for what purpose you would use it for. Wh

相关标签:
2条回答
  • 2021-01-05 23:27

    Writing file on hard-drive one character per time is inefficient. Sending a packet over network for each character is inefficient. Therefore streaming is often cached. flush() is just a way to control "manually" during streaming when the cache must be flushed and the stuff should be really sent or written.

    0 讨论(0)
  • 2021-01-05 23:37

    In all likelihood, the word flush comes from exactly what you'd flush in real-life. A toilet...

    So let's try a toilet analogy:

    Flushing every time a new one drops into the bowl is very time-consuming and a complete waste of water. That's a big problem today where everyone's trying to be environmentally friendly.

    So what do you do instead? You buffer it by saving it all up and flushing once at the end. If for whatever reason, you can always "prematurely" flush somewhere in the middle when you're not done.


    C++ streams (among other things) work much the same way. To reduce overhead and improve performance, a stream buffers its contents and only periodically "flushes" it. The draw-back of this is that you may get "delayed" behavior like in this question: Why does printf not flush after the call unless a newline is in the format string?

    So that's what flush() is for. To allow you to override the buffering.

    0 讨论(0)
提交回复
热议问题