std::flush
right after a std::endl
is used all over the legacy code I am looking at. When I first saw this, my thought was it is redundant from looking at the description of std::endl
and std::flush
at:
http://en.cppreference.com/w/cpp/io/manip/endl
http://en.cppreference.com/w/cpp/io/manip/flush
Here is an example of what I am seeing in the legacy source code:
std::cout << "Generic Notification" << std::endl << std::flush;
But, as many senior software developers have seen this code throughout the years, I am wondering if there is some detail I am missing. Is there any purpose to having a std::flush
after a std::endl
?
std::endl writes a newline to the output stream and flushes it. In most cases, the developer doesn't need to flush. Flushing operation is expensive, because it involves a system call.
There is rarely a need for std::endl , and getting in the habit of using it will lead to mysteriously slow code. Just use '\n' unless you know you need to flush the buffer. Save this answer.
std::flushFlushes the output sequence os as if by calling os. flush(). This is an output-only I/O manipulator, it may be called with an expression such as out << std::flush for any out of type std::basic_ostream.
We use std::endl for creating a newline after the current line. For few lines of IO operations, it is not making any problems.
I'll add to the other valid answers that, very often, there isn't a good purpose for either std::flush
nor std::endl
.
Basically, std::endl
= start a new line + flush the stream. A lot of people, though, tend to end their lines with std::endl
because it "sounds right" - end the line. But we actually rarely need to flush the output stream. Sometimes we do (e.g. when we're expecting a user's reply to the string, or it's important to monitor our output with minimal delay) - but that's the exception, not the rule.
So, it might take a bit of getting used to, but we should really default to simply:
std::cout << bunch_of_stuff << '\n';
and that's that!
There's no purpose for it.
If I had to speculate on why your legacy code contains these lines, there are a few possibilities, starting with (what I consider to be) the most probable scenarios:
std::flush
mistakenly, and the senior developers didn't consider it a problem needing fixingstd::endl
did not trigger a flush, which meant that your senior developers were (correctly) understanding that it was necessarystd::endl
to trigger a flushstd::endl
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With