The consequences and pros/cons of flushing the stream in c++

后端 未结 5 1793
心在旅途
心在旅途 2021-01-01 11:16

I have recently read an article which stated that using \\n is preferable to using std::endl because endl also flushes the stream.

5条回答
  •  醉话见心
    2021-01-01 11:36

    It will be preferable in any situation in which you want the output to actually appear exactly when it was supposed to appear.

    A simple example:

    #include 
    int main() {
        std::cout << "Please enter your name: " << std::endl;
        std::string name;
        std::cin >> name;
        ...
    }
    

    With buffering, no text will appear on screen before the user is expected to type his/her name, so the user will be confused. (Note that in fact it might be really difficult or impossible to get this example run with buffering fully enabled, as C++ might take special measures to flush std::cout before any input from std::cin, see Why do we need to tie std::cin and std::cout?. But this is just a theoretical example: in case the buffering is fully enabled, the user will not see the prompt.)

    Such a situation can occur from time to time, though it might not be very often. Consider writing to a pipe to interact with another process. Or even if your program writes to log file and you personally look into the log file from time to time to see how it runs --- in case of buffering, you usually will not see the output that has been printed from program, but still stays in the buffer yet.

    Another important situation to account for --- if your program severely crashes, the buffer contents might not end on the hard drive at all. (I expect the stream destructors to flush the buffer, but a crash can be so severe that no destructors will be called at all.)

提交回复
热议问题