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
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.
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.