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

后端 未结 5 1778
心在旅途
心在旅途 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:26

    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 been crashed before the actual logging.

提交回复
热议问题