What does flushing the buffer mean?

試著忘記壹切 提交于 2019-12-17 05:37:57

问题


I am learning C++ and I found something that I can't understand:

Output buffers can be explicitly flushed to force the buffer to be written. By default, reading cin flushes cout; cout is also flushed when the program ends normally.

So flushing the buffer (for example an output buffer): does this clear the buffer by deleting everything in it or does it clear the buffer by outputting everything in it? Or does flushing the buffer mean something completely different?


回答1:


Consider writing to a file. This is an expensive operation. If in your code you write one byte at a time, then each write of a byte is going to be very costly. So a common way to improve performance is to store the data that you are writing in a temporary buffer. Only when there is a lot of data is the buffer written to the file. By postponing the writes, and writing a large block in one go, performance is improved.

With this in mind, flushing the buffer is the act of transferring the data from the buffer to the file.

Does this clear the buffer by deleting everything in it or does it clear the buffer by outputting everything in it?

The latter.




回答2:


You've quoted the answer:

Output buffers can be explicitly flushed to force the buffer to be written.

That is, you may need to "flush" the output to cause it to be written to the underlying stream (which may be a file, or in the examples listed, a terminal).

Generally, stdout/cout is line-buffered: the output doesn't get sent to the OS until you write a newline or explicitly flush the buffer. The advantage is that something like std::cout << "Mouse moved (" << p.x << ", " << p.y << ")" << endl causes only one write to the underlying "file" instead of six, which is much better for performance. The disadvantage is that a code like:

for (int i = 0; i < 5; i++) {
    std::cout << ".";
    sleep(1); // or something similar
}

std::cout << "\n";

will output ..... at once (for exact sleep implementation, see this question). In such cases, you will want an additional << std::flush to ensure that the output gets displayed.

Reading cin flushes cout so you don't need an explicit flush to do this:

std::string colour;
std::cout << "Enter your favourite colour: ";
std::cin >> colour;



回答3:


Clear the buffer by outputting everything.



来源:https://stackoverflow.com/questions/15042849/what-does-flushing-the-buffer-mean

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