C++是什么? iostream endl 惨败?
当我正在听 Andrei Alexandrescu 关于 D 编程的 Google 演讲时,他放弃了关于“endl”惨败的一则短文。我只是认为 endl 是表示行结束和刷新流缓冲区的首选方式。为什么它被认为是一场惨败?我不应该在我的代码中使用它吗?
I was listening to a google talk by Andrei Alexandrescu on the D programming language when he threw out a one liner about the "endl" fiasco. I just thought endl was the preferred way to signify the end of a line and flush the buffer for a stream. Why is it considered a fiasco? Should I not be using it in my code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
(我认为)他只是意味着许多,尤其是新的 C++ 程序员盲目地使用
std::endl
而不是'\n'
来换行,不必要地频繁刷新,并可能使他们的程序的性能很糟糕。也就是说,大多数人都被告知
std::endl
是在流中插入换行符的规范方法,尽管它很少有必要或适当冲洗。有些人认为(*咳嗽*)
std::endl
甚至不应该出现在标准中,因为它很少适用,并且不会节省显着的打字量超过'\n' <<无论如何,std::flush
。TL;DR(s):
std::endl
除了通常更差性能之外什么也没有给你带来通常需要更多的打字。(I assume) He just means that many, especially new, C++ programmers use
std::endl
blindly instead of'\n'
for newline, flushing unnecessarily frequently and potentially making the performance of their program abysmal.I.e., most people are taught that
std::endl
is the canonical way to insert a newline into a stream even though it is very rarely necessary or appropriate to flush it.It is some people's opinion (*cough*) that
std::endl
shouldn't even be in the standard, as it is so rarely appropriate and not a significant typing savings over'\n' << std::flush
anyway.TL;DR(s):
std::endl
buys you nothing except usually worse performance and usually more typing.为了补充已经很好的答案,这个问题可以扩展到“iostream”惨败。
一般来说,使用 iostream 会带来性能损失,因为它被设计为与 stdio 流(
printf
和scanf
)同步,以便您可以混合使用 isotream 和 stdio如果需要的话。如果您只打算使用一个,则可以通过调用
std::ios::sync_with_stdio(false)
来获得性能优势。然而,我相信,未同步的流不再是线程安全的......请参阅此处和此处以及文档这里。
To add to the already great answer, this issue can be extended to the 'iostream' fiasco.
Using iostream in general has a performance penalty because it is designed to be synced up with the stdio streams (
printf
andscanf
) so that you can use a mix of isotream and stdio if so desired.If you are only going to be using one you can get a performance benefit by calling
std::ios::sync_with_stdio(false)
. I believe, however, the unsynced streams are no longer thread safe...See more here and here as well as documentation here .