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

2

6

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. Why not call flush(), every time your write to the stream?

Footstalk answered 9/9, 2012 at 2:20 Comment(1)
Buffering is faster than raw throughput: en.wikipedia.org/wiki/Data_buffer. The rollercoaster analogy in that article is actually quite good.Ance
I
28

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.

Ictus answered 9/9, 2012 at 2:37 Comment(1)
I hope I don't have to supplement this with a picture and benchmarks.Ictus
D
1

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.

Dakota answered 9/9, 2012 at 2:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.