Search code examples
c++flushendl

Does std::endl << std::flush have a purpose?


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?


Solution

  • 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:

    • Someone added the explicit call to std::flush mistakenly, and the senior developers didn't consider it a problem needing fixing
    • The code originates from a time before the C++ standard was widely adopted, and in that time, the local compiler's implementation of std::endl did not trigger a flush, which meant that your senior developers were (correctly) understanding that it was necessary
    • An older version of the C++ standard might not have required std::endl to trigger a flush
    • Your senior developers are mistaken about the behavior of std::endl.
    • Your execution environment is a strange behemoth that actually requires output to be flushed twice before the desired result can be expected.