Quantcast
Channel: User Marco A. - Stack Overflow
Viewing all articles
Browse latest Browse all 45

Answer by Marco A. for The consequences and pros/cons of flushing the stream in c++

$
0
0

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 bufferedbash: 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.


Viewing all articles
Browse latest Browse all 45

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>