When must the output stream in C++ be flushed?

后端 未结 6 1094
执笔经年
执笔经年 2021-01-21 21:45

I understand cout << \'\\n\' is preferred over cout << endl; but cout << \'\\n\' doesn\'t flush the output stream. When

6条回答
  •  别那么骄傲
    2021-01-21 22:11

    First, you read wrong. Whether you use std::endl or '\n' depends largely on context, but when in doubt, std::endl is the normal default. Using '\n' is reserved to cases where you know in advance that the flush isn't necessary, and that it will be too costly.

    Flushing is involved with buffering. When you write to a stream, (typically) the data isn't written immediately to the system; it is simply copied into a buffer, which will be written when it is full, or when the file is closed. Or when it is explicitly flushed. This is for performance reasons: a system call is often a fairly expensive operation, and it's generally not a good idea to do it for every characters. Historically, C had something called line buffered mode, which flushed with every '\n', and it turns out that this is a good compromize for most things. For various technical reasons, C++ doesn't have it; using std::endl is C++'s way of achieving the same results.

    My recommendation would be to just use std::endl until you start having performance problems. If nothing else, it makes debugging simpler. If you want to go further, it makes sense to use '\n' when you're outputting a series of lines in just a few statements. And there are special cases, like logging, where you may want to explicitly control the flushing.

提交回复
热议问题