Search code examples
c++bufferiostream

Is `clog` buffered?


I have read in many places that clog is the same as cerr, except that clog is buffered and cerr is not. But I cannot see this behavior on my computer (Ubuntu 20.04, clang 9). Here is the code I use:

clog << "AA";
this_thread::sleep_for(chrono::seconds(3));
clog << endl;
clog << "BB" << endl;

When I use cout instead of clog, I do not see anything in the first 3 seconds; then I immediately see AA and BB.

When I use cerr instead of clog, I see immediately AA, then after 3 seconds I see BB.

When I use clog, I see exactly as with cerr --- immediately AA, then after 3 seconds I see BB.

If clog is buffered, shouldn't it behave like cout?

Is this a bug in my compiler?


Solution

  • It's not a bug, clog is not supposed to be buffered, in fact the standard does not associate clog with cout in any way nor does it state tha clog should be buffered.

    It does state that cerr and clog are both associated with stderr, so if there was to be some similarity in the behavior it should be between clog and cerr, which seems to be what you are experiencing.

    As stderr is defined to be unbuffered it would be logical that clog is also unbuffered, but as this behavior isn't specified, it is not guaranteed to be always the case.

    cout is associated with stdout, and its buffering settings are deppendent on the environment. Usually, for UNIX systems, it's line buffered.

    29.4.3 Narrow stream objects [narrow.stream.objects]

    ostream cout;

    3 - The object cout controls output to a stream buffer associated with the object stdout, declared in <cstdio>(29.12.1).

    ostream cerr;

    4 - The object cerr controls output to a stream buffer associated with the object stderr, declared in <cstdio>(29.12.1).

    [...]

    ostream clog;

    6 - The object clog controls output to a stream buffer associated with the object stderr, declared in <cstdio>(29.12.1).