endl

742阅读 0评论2008-10-24 wqfhenanxc_cu
分类:C/C++


   endl在C++中使用时一般用在ostream的子类中,使用方法如

            1   cout << "It's a wonderful life!" << endl;

  这时除在标准输出打印出It's a wonderful life!外, cout类还要将自己的
缓冲区清空,类似C的fflush( stdout ),而

            2   cout << "It's a wonderful life!" << "\n";

却不会有这一动作, 这样在某些情况下语句2将不能打印出要求内容,因为它们还在
cout的缓冲区中.
如果你想深入了解iostream类的实现,可以看看其源文件,相信会对你的编程能力有较大的提高。或者阅读the c++ programming language的iostream(好象是第八章)一章。

endl和'\n'的区别很简单,就是endl会多一个刷缓冲的操作
因此endl会带来一些性能上的问题
基本的原则是
prefer '\n' to endl
或者说
only use endl when necessary
endl实现的头文件ostream中有专门的注释说明,但是应该没什么人会注意到... 上代码(from ostream头文件):

 
 
// [27.6.2.7] 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
   *   for more
   *  on this subject.
  */


上一篇:cerr cout clog 的区别
下一篇:命名空间 转载