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

给你一囗甜甜゛ 提交于 2019-12-19 03:46:33

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/12336035/in-simple-terms-what-is-the-purpose-of-flush-in-ostream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!