Will an ostream flush other stream?

Viewed 74

I'm curious about why I output by different ostream, and don't flush them, but when program exited, they won't mess up the order, does an ostream flush others stream?how C++ standard library make they communicate?

#include <iostream>

int main()
{
    std::clog << "flush test1 by clog\n";
    std::cout << "flush test1 by cout\n";
    std::cout << "flush test2 by cout\n";
    std::clog << "flush test2 by clog\n";
    return 0;
}

/* The output is
 * flush test1 by clog
 * flush test1 by cout
 * flush test2 by cout
 * flush test2 by clog
 */
1 Answers

The clog stream is usually the same as the cerr stream, which is, depending on your library either line-buffer or not buffered meaning that at least after a line break (\n) it is written onto your terminal. cout on the other hand might be either fully buffered (only written if the buffer is full or flushed), line-buffered or not buffered. Even more specific from cplusplus.com: ("If stdout is known to not refer to an interactive device, the stream is fully buffered. Otherwise, it is library-dependent whether the stream is line buffered or not buffered by default."). Assuming your terminal is interactive, the cout buffer is written to your termial at least after every line.

Related