在c ++中刷新流的后果和优点/缺点 [英] The consequences and pros/cons of flushing the stream in c++

查看:216
本文介绍了在c ++中刷新流的后果和优点/缺点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近读过一篇文章,指出使用 \\\
比使用 std :: endl 因为 endl 也会刷新流。

但是当我查找有关该主题的更多信息时,我发现了一个网站:

I have recently read an article which stated that using \n is preferable to using std::endl because endl also flushes the stream.
But when I looked for a bit more information on the topic I found a site which stated:


如果你在一个你必须避免缓冲的情况下,你可以使用std :: endl而不是'\\\
'

If you are in a situation where you have to avoid buffering, you can use std::endl instead of ‘\n’

这里有我的问题:在哪种情况下,最好缓冲区?因为我只看到了这种技术的优势。是不是也更安全写入缓冲区?因为它小于硬盘驱动器,它会被覆盖的速度比存储在HD上的数据(我不知道如果这是真的)。

Now here comes my question: In which situation is it preferable not to write to the buffer? Because I only saw advantages of that technique. Isn't it also safer to write to the buffer? Because it is smaller than a hard drive it will get overwritten faster than data that is stored on the HD (I am not sure if this is true).

推荐答案

当发生缓冲时,您不能保证在发生刷新之前立即接收到数据。在特定情况下,您可能会遇到错误的输出顺序和/或信息/调试数据丢失,例如

When buffering occurs you will have no guarantees that the data is immediately received before a flush occurs. Under particular circumstances you might experience wrong output ordering and/or loss of information/debug data, e.g.

int main() {

    std::cout << "This text is quite nice and might as well be buffered";
    raise(SIGSEGV); // Oh dear.. segmentation violation
    std::cout << std::endl;
}

实例

输出:

bash: line 7: 22235 Segmentation fault      (core dumped) ./a.out


b $ b

上述会打印任何文本,因为缓冲会阻止正确的输出显示。

the above will not print any text since the buffering prevented the right output to be displayed.

在缓冲区末尾添加一个刷新 std :: endl 这是您获得的

Now if you simply add a flushing std::endl at the end of the buffer this is what you get

int main() {

    std::cout << "This text is quite nice and might as well be buffered" << std::endl;
    raise(SIGSEGV); // Oh dear.. segmentation violation
    std::cout << std::endl;
}

实例

输出:

This text is quite nice and might as well be buffered
bash: line 7: 22444 Segmentation fault      (core dumped) ./a.out

这次输出在程序终止之前之前是可见的。

This time the output is visible before the program termination.

这个事实的影响是多方面的。纯粹推测:如果数据与服务器日志相关,您的应用程序可能在实际日志记录之前崩溃。

Implications of this fact are manifold. Purely speculative: if the data were related to a server log, your app could have been crashed before the actual logging.

这篇关于在c ++中刷新流的后果和优点/缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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