C++是什么? iostream endl 惨败?

发布于 2024-10-28 09:39:19 字数 205 浏览 2 评论 0原文

当我正在听 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅黛梨妆こ 2024-11-04 09:39:19

(我认为)他只是意味着许多,尤其是新的 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):

  • In the end, std::endl buys you nothing except usually worse performance and usually more typing.
  • It has its uses, but they are considerably rarer than its frequency of use in most large codebases would suggest, therefore...
  • Its utility is highly questionable and its ubiquity is absurd – a fiasco indeed!
第几種人 2024-11-04 09:39:19

为了补充已经很好的答案,这个问题可以扩展到“iostream”惨败。

一般来说,使用 iostream 会带来性能损失,因为它被设计为与 stdio 流(printfscanf)同步,以便您可以混合使用 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 and scanf) 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 .

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文