Search code examples
c++theoryflush

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


I have recently read an article which stated that using \n is preferable to using std::endl because endl also flushes the stream.
But when I looked for a bit more information on the topic I found a site which stated:

If you are in a situation where you have to avoid buffering, you can use std::endl instead of ‘\n’

Now here comes my question: In which situation is it preferable not to write to the buffer? Because I only saw advantages of that technique. Isn't it also safer to write to the buffer? Because it is smaller than a hard drive it will get overwritten faster than data that is stored on the HD (I am not sure if this is true).


Solution

  • When buffering occurs you will have no guarantees that the data is immediately received before a flush occurs. Under particular circumstances you might experience wrong output ordering and/or loss of information/debug data, e.g.

    int main() {
       
        std::cout << "This text is quite nice and might as well be buffered";
        raise(SIGSEGV); // Oh dear.. segmentation violation
        std::cout << std::endl;
    }
    

    Live Example

    Output:

    bash: line 7: 22235 Segmentation fault      (core dumped) ./a.out
    

    the above will not print any text since the buffering prevented the right output to be displayed.

    Now if you simply add a flushing std::endl at the end of the buffer this is what you get

    int main() {
       
        std::cout << "This text is quite nice and might as well be buffered" << std::endl;
        raise(SIGSEGV); // Oh dear.. segmentation violation
        std::cout << std::endl;
    }
    

    Live Example

    Output:

    This text is quite nice and might as well be buffered
    bash: line 7: 22444 Segmentation fault      (core dumped) ./a.out
    

    This time the output is visible before the program termination.

    Implications of this fact are manifold. Purely speculative: if the data were related to a server log, your app could have crashed before the actual logging.