简体   繁体   English

std::endl 不是多余的吗?

[英]Isn't std::endl redundant?

Flush happens in the following cases:刷新发生在以下情况:

  • std::cerr标准::cerr
  • std::cin标准::辛
  • program termination程序终止
  • in many implementations, standard output is line-buffered, meaning "\\n" flushes anyway在许多实现中,标准输出是行缓冲的,这意味着“\\n”无论如何都会刷新

So it seems in most regular programs, std::endl is basically unnecessary, but it's used almost everywhere.所以看起来在大多数常规程序中,std::endl 基本上是不必要的,但它几乎无处不在。

std::cerr标准::cerr

But what if I do not want to write to stderr, but rather stdout?但是如果我不想写入 stderr 而是 stdout 呢?

std::cin标准::辛

But what if I just want to give the user some status update and do not want any input?但是如果我只想给用户一些状态更新而不想要任何输入怎么办?

program termination程序终止

As above, what if I want to tell the user something before the program is done?如上,如果我想在程序完成之前告诉用户一些事情怎么办?

in many implementations, standard output is line-buffered, meaning "\\n" flushes anyway在许多实现中,标准输出是行缓冲的,这意味着“\\n”无论如何都会刷新

But what about the platforms that don't?但是那些没有的平台呢? Regardless of whether or not such a platform currently exists, I want my code to work as intended as defined by the standard, not as by "meh, will probably be fine on all implementations".无论当前是否存在这样的平台,我都希望我的代码按照标准定义的那样工作,而不是像“嗯,在所有实现上都可能会很好”那样工作。

If all of the above apply (the fourth point actually always applies), you need to flush "by hand".如果以上所有情况都适用(第四点实际上始终适用),则需要“手动”冲洗。 If the flush gets handled by one of the first three, you don't.如果冲洗由前三个之一处理,则不会。

So it seems in most regular programs, std::endl is basically unnecessary, but it's used almost everywhere.所以看起来在大多数常规程序中, std::endl基本上是不必要的,但它几乎无处不在。

No it's not redundant , since implementation of flushing along '\\n' isn't mandated by the standard.不,这不是多余的,因为标准没有强制要求沿'\\n'实现刷新。 That's just an implementation specific behavior, while the behavior of std::endl is always clearly defined.这只是一个实现特定的行为,而std::endl的行为总是明确定义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM