问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/3780898/how-are-iostream-objects-cin-cout-cerr-and-clog-implemented