许多C++书籍都包含像这样的示例代码...
std::cout << "Test line" << std::endl;
...所以我一直都是这样做的。但我看到很多工作开发人员的代码却是这样的:
std::cout << "Test line\n";
你认为是出于技术原因还是仅仅是编码风格的选择?
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";
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'))); }
'\n'
。 - derobertendl
语句。特别是当你将许多短行或像我经常看到的单个字符写入文件时。使用endl
已知会破坏像 NFS 这样的网络文件系统。 - John Damm Sørensen