C++ Primer 4/e在Managing the Output Buffer这个地方有一个警告:‘Output buffers are not flushed if the program terminates abnormally. When attempting to debug a program that has crashed, we often use the last output to help isolate the region of program in which the bug might occur. If the crash is after a particular print statement, then we know that the crash happened after that point in the program.
When debugging a program, it is essential to make sure that any output you think should have been written was actually flushed. Because the system does not automatically flush the buffers when the program crashes, it is likely that there is output that the program wrote but that has not shown up on the standard output. It is still sitting in an output buffer waiting to be printed.
If you use the last output to help locate the bug, you need to be certain that all the output really did get printed. Making sure that all output operations include an explicit flush or call to endl is the best way to ensure that you are seeing all the output that the program actually processed.
Countless hours of programmer time have been wasted tracking through code that appeared not to have executed when in fact the buffer simply had not been flushed. For this reason, we tend to use endl rather than \n when writing output. Using endl means we do not have to wonder whether output is pending when a program crashes.’
中文版的这样写:‘如果程式未能正常终止,output缓冲区并不会被清空。欲对非正常终止的程式侦错,我们经常以“最后一个输出”协助隔离可能的臭虫发生区域。一旦在某特定列印述句后当掉,我们就知道问题是由该点之后的程式码引起。
对程式侦错时,很重要的一件事是“确认应该写出的任何讯息都已被扫出缓冲区”。这是因为程式当掉时系统并不自动清空缓冲区,因此也许程式写出了讯息但未显示于标准输出装置上-它仍置于output缓冲区等待被印出。
如果你以上述的“最后一个输出”协助定出臭虫位置,必须确认所有输出讯息真的都要被印出了。最好的办法就是确保每一个输出操作都包含一个明确的flush或endl。
程式员的工作生命中有无数小时浪费在追踪似乎并没有被执行起来的程式码,而其实那也许只是缓充区没被清空而已。因为这个原因,我们在输出讯息时倾向使用endl而非’\n’,这可使我们在程式当掉时不需考虑output缓冲区到底有没有被清空。’
缓冲区的flush及endl还满玄的,好像我没什么印象出错过,好吧记起来以备已后用到。