What does std::flush really do?

When looking at videos and tutorial text flush seems to be used as a way to empty the stream, to not risk of having characters etc end up in places you did not intend to. But when you look at the documentation it says..

"Synchronizes the associated stream buffer with its controlled output sequence.

For stream buffer objects that implement intermediate buffers, this function requests all characters to be written to the controlled sequence."

I don't really understand what they mean, maybe som clarification from a more senior programmer?
std::flush applied to an output stream writes out pending output (characters that may still be in the streams buffer in memory, and have not been written out as yet).

This manipulator may be used to produce an incomplete line of output immediately, e.g. when displaying output from a long-running process, logging activity of multiple threads or logging activity of a program that may crash unexpectedly. An explicit flush of std::cout is also necessary before a call to std::system, if the spawned process performs any screen I/O (a common example is std::system("pause") on Windows).

https://en.cppreference.com/w/cpp/io/manip/flush#Notes

To flush a complete line of output, we could use std::endl
These do the same thing:
1
2
std::cout << "hello world!" << '\n' << std::flush ;
std::cout << "hello world!" << std::endl ;


In a usual interactive program, std::endl or std::flush on std::cout is unnecessary; std::cout is flushed before every input operation on std::cin
Also note that std::cerr automatically flushes after write. https://en.cppreference.com/w/cpp/io/cerr
I have only really noticed a need to flush when debugging
say you have a crash, and the output on the screen is not up to date: you can see in the debugger it was farther along, but it is not on the output screen yet...

its rare for me to need it on cout apart from the above, but note that cout is a stream. There are plenty of time when you need to flush a stream or file to be sure it is up to date.
Closing a file stream automatically does a flush.
> There are plenty of time when you need to flush a stream or file to be sure it is up to date.

Yes; for instance if we are writing a transaction log.

In many cases, it is simpler to enable automatic flushing with std::unitbuf
https://en.cppreference.com/w/cpp/io/manip/unitbuf
Topic archived. No new replies allowed.