平常在使用的时候,如果程序不复杂,其实endl和\n在使用效果上没有什么区别,实际上,作为一个流操作符,endl比起\n多了一项功能,那就是刷新输出缓冲区。
从简单的平时使用来看
我们平时使用的:
std::cout<<std::endl;
可以简单的理解为:
std::cout << '\n' << std::flush
使用cout
代替\n
的好处是,由于输出流缓冲区在被填满的时候会自动刷新输出,可能会造成不必要的输出麻烦。但其实普通的cout
相对于文件输出流而言,其实并没有太大必要使用endl。
很明显,endl是给具有缓冲区的流设计的,像cerr
这样的无缓冲流就不用\n
换行了。
从endl的源代码来看
endl包含在ostream库当中
利用搜索功能我们可以找到如下源代码
/**
* @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'))); }
可见endl实际是名字空间std中的一个全局内联函数(记住std::endl是一个函数),它做了两件事:
- 输出一个换行符
- 调用flush。
再看看flush
/**
* @brief Flushes the output stream.
*
* This manipulator simply calls the stream's @c flush() member function.
*/
template<typename _CharT, typename _Traits>
inline basic_ostream<_CharT, _Traits>&
flush(basic_ostream<_CharT, _Traits>& __os)
{
return __os.flush(); // 注意这里的os不是操作系统的意思,而是类basic_ostream的缩写
}
这里的flush是std::basic_ostream::flush
/**
* @file ostream.tcc
*/
template<typename _CharT, typename _Traits>
basic_ostream<_CharT, _Traits>&
basic_ostream<_CharT, _Traits>::flush()
{
// _GLIBCXX_RESOLVE_LIB_DEFECTS
// DR 60. What is a formatted input function?
// basic_ostream::flush() is *not* an unformatted output function.
ios_base::iostate __err = ios_base::goodbit;
__try
{
// 刷新发生在pubsync,底层调用的是LIBC库函数fflush
if (this->rdbuf() && this->rdbuf()->pubsync() == -1)
__err |= ios_base::badbit;
}
__catch(__cxxabiv1::__forced_unwind&)
{
this->_M_setstate(ios_base::badbit);
__throw_exception_again;
}
__catch(...)
{
this->_M_setstate(ios_base::badbit);
}
if (__err)
this->setstate(__err);
return *this;
}
便是整个endl操作符的机理。
tips:“cout” is pronounced “see-out” The "c stands for “character” because iostreams map values to and from byte (char) representations.