gpt4 book ai didi

c++ - 应该始终使用 std::endl 吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:37:08 26 4
gpt4 key购买 nike

C++ Primer(第 5 版)一书的帮助下,我从 C 跳转到了 C++,其中作者陈述如下:

Programmers often add print statements during debugging. Such statements should always flush the stream. Otherwise, if the program crashes, output may be left in the buffer, leading to incorrect inferences about where the program crashed.

但网上的帖子表明情况并非如此;有人说不断刷新缓冲区对程序不利并导致性能问题。

我的问题:

  1. 什么时候应该使用std::endl
  2. 是作者错了还是我误解了他所说的任何部分?
  3. 您能否提供任何需要刷新输出流的真实场景?

附言

  1. 刷新缓冲区是什么意思?

最佳答案

调试输出应写入std::cerr;它是单位缓冲的,所以每个字符都会被刷新。很少需要 std::endl,养成使用它的习惯会导致代码异常缓慢。除非您知道需要刷新缓冲区,否则只需使用 '\n'

关于c++ - 应该始终使用 std::endl 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35580919/

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