Why does endl get used as a synonym for “\\n” even though it incurs significant performance penalties?

杀马特。学长 韩版系。学妹 提交于 2019-12-01 17:13:49
CB Bailey

I'm not certain. Inserting std::endl into the output stream is defined as being equivalent to inserting .widen('\n') and then calling flush() and yet many programmers persist in using std::endl even when there is no cause to flush, for example they go on to immediately output something else.

My assumption is that it comes from an incorrect belief that it is somehow a more portable because it doesn't explicitly use a specific newline character. This is incorrect as \n must always be mapped to the system's correct newline sequence for non-binary files by the stream library.

Afaik, endl also flushes the stream, which may be the cause of the performance penalty.

Not everyone cares so much about performance. For some applications, guaranteeing the stream is flushed is much more important.

Edit: Also, I find endl easier to type than '\n' :-)

I tend to use endl with on stringstreams as it makes it easy to spot missing linebreaks.

My guess is that instructional texts use std::endl with the belief that it's simpler and less confusing for beginners, and afterward people got accustomed to using it.

The real question is, why did the compiler make such a dogs breakfast of compiling the endl version? If they're guaranteed to have the same semantics, then they should also have the same runtime.

Edit: obviously, I wasn't aware that endl flushed the stream... that's what you get for not looking it up.

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