How are iostream objects cin, cout, cerr, and clog implemented?

混江龙づ霸主 提交于 2019-12-14 03:42:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!