views:

73

answers:

1

iostream objects cin, cout, cerr, and clog are objects declared in the iostream header.

I'm aware that it's possible in some compilers to attempt to use these iostream objects before they are constructed, so under some circumstances they must be subject to the "static initialisation order fiasco". In those compilers where it's always safe to use std::cout et al, how do these objects actually get constructed? Does it involve under-the-hood compiler magic or could it in principle all be done with standard C++?

std::cout etc seem to be either global variables or singleton: why are global variables and singletons usually considered evil but seemingly not in this particular case?

+2  A: 

There's no compiler magic.

IIRC, the standard implementation is to define a global constant object in the header. In each translation unit this header is included, one such object is created. Its constructor increments a counter, its destructor decrements it. When incrementing from 0 to 1, the the console stream objects are created, when decrementing from 1 to 0, they are destroyed.

sbi
This idiom has a name, too: http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Nifty_Counter
Cubbi
Thanks - I wasn't aware of the nifty / Schwarz Counter idiom.
Simon Elliott