"std::endl"与"\n"的区别

707
许多C++书籍都包含像这样的示例代码...
std::cout << "Test line" << std::endl;

...所以我一直都是这样做的。但我看到很多工作开发人员的代码却是这样的:

std::cout << "Test line\n";

你认为是出于技术原因还是仅仅是编码风格的选择?


15
好的解释:http://cppkid.wordpress.com/2008/08/27/why-i-prefer-n-to-stdendl/ - Payton Millhouse
32
@derobert 这个比另一个旧。 - Kira
8
@HediNaily确实是这样。但是,另一个答案让我觉得略微更好,所以我选择采用那种方式。而且,另一个答案的范围略微更广,也包括'\n' - derobert
如果你打算在自己的笔记本电脑以外的任何设备上运行程序,绝对不要使用 endl 语句。特别是当你将许多短行或像我经常看到的单个字符写入文件时。使用 endl 已知会破坏像 NFS 这样的网络文件系统。 - John Damm Sørensen
可能会有显著的性能差异。 - qwr
11个回答

0
GCC文档中得知:
有些人认为在输出流中发送endl只会写入一个换行符。这是错误的;在写入换行符后,缓冲区也会被刷新。也许当你写入屏幕时,你想要的效果就是尽快将文本显示出来等等,但是当你对文件进行这样的操作时,缓冲几乎是浪费的。
output << "a line of text" << endl;
output << some_data_variable << endl;
output << "another line of text" << endl; 

在这种情况下,正确的做法是将数据写出,让库和系统来处理缓冲。如果你需要换行,就写一个换行符。
output << "a line of text\n"
<< some_data_variable << '\n'
<< "another line of text\n"; 

您可以查看ostream的文档,或者查看endl的实现本身-在我的情况下,位于usr/include/c++/11/ostream:684。那里你会找到:
  // Standard basic_ostream manipulators

  /**
   *  @brief  Write a newline and flush the stream.
   *
   *  This manipulator is often mistakenly used when a simple newline is
   *  desired, leading to poor buffering performance.  See
   *  https://gcc.gnu.org/onlinedocs/libstdc++/manual/streambufs.html#io.streambuf.buffering
   *  for more on this subject.
  */
  template<typename _CharT, typename _Traits>
    inline basic_ostream<_CharT, _Traits>&
    endl(basic_ostream<_CharT, _Traits>& __os)
    { return flush(__os.put(__os.widen('\n'))); }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接