gpt4 book ai didi

c++ - 在 C++ 中刷新流的后果和优缺点

转载 作者:IT老高 更新时间:2023-10-28 12:55:44 25 4
gpt4 key购买 nike

我最近阅读了一篇文章,其中指出使用 \n 比使用 std::endl 更可取,因为 endl 也会刷新流.
但是当我寻找有关该主题的更多信息时,我发现了一个网站,上面写着:

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

现在我的问题来了:在哪种情况下最好写入缓冲区?因为我只看到了这种技术的优点。写入缓冲区不是也更安全吗?因为它比硬盘驱动器小,它会比存储在 HD 上的数据更快地被覆盖(我不确定这是否属实)。

最佳答案

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

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;
}

Live Example

输出:

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

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

现在,如果您只是在缓冲区末尾添加一个刷新 std::endl 这就是您得到的

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;
}

Live Example

输出:

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

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

这一事实的含义是多方面的。纯属推测:如果数据与服务器日志相关,那么您的应用可能在实际日志记录之前就崩溃了。

关于c++ - 在 C++ 中刷新流的后果和优缺点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29701302/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com