简单来说,ostream中flush()的目的是什么 [英] In simple terms, what is the purpose of flush() in ostream

查看:468
本文介绍了简单来说,ostream中flush()的目的是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据以下定义定义: http://www.cplusplus.com/reference/iostream/ostream/flush/,尚不清楚该功能为何存在,以及将其用于什么目的.为什么每次写入流时不调用flush()?

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?

推荐答案

flush一词很可能完全来自您在现实生活中会冲洗的东西.厕所...

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 ++流(除其他外)的工作方式几乎相同.为了减少开销并提高性能,流将缓冲其内容,并仅定期对其进行刷新".这样做的缺点是,您可能会出现类似以下问题的延迟"行为:

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?

这就是flush()的用途.为了让您覆盖缓冲.

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

这篇关于简单来说,ostream中flush()的目的是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆