Path: utzoo!utgpu!news-server.csri.toronto.edu!bonnie.concordia.ca!uunet!taumet!steve From: steve@taumet.com (Stephen Clamage) Newsgroups: comp.lang.c++ Subject: Re: cout in static object constructors Message-ID: <746@taumet.com> Date: 24 May 91 17:08:21 GMT References: <76LR01ly7a2m00@amdahl.uts.amdahl.com> Organization: Taumetric Corporation, San Diego Lines: 63 lms@uts.amdahl.com (Linda Sorauf) writes: >Basically, I have been warned against using cout >in constructors of static objects. Apparently, >cout, which is itself not static, relies on a >static object called iostream_init. The danger >is that the order of static object construction >may be such that cout is used before iostream_init >has been constructed. There is a general problem with constructors of static objects referring to other objects. There is no way to guarantee the order of such constructors when they occur in different compilation units. (No portable way, at least.) With this in mind, iostreams were carefully designed to guarantee that the standard streams are all initialized before any user-defined objects are constructed, PROVIDED that you #include (or some file which includes it, such as or ) ahead of any static object which needs to use a standard stream. Example 1 (all in one file) will always work: #include class C { public: C(); // ... }; C c; C::C() { ... cout << "hello\n"; } Example 2 (all in one file) will compile and link, but may or may not work: class C { public: C(); // ... }; C c; #include C::C() { ... cout << "greetings from C\n"; } Example 3 (two files) will compile and link, but may or may not work: file1.c: class C { public: C(); // ... }; C c; file2.c: #include C::C() { ... cout << "greetings from C\n"; } Examples 2 and 3 will work if by chance cout gets constructed before the constructor for c gets called. You cannot in general predict whether this will happen. You can make Example 2 work by moving the include to the top of the file. You can make Example 3 work by including in file1.c. -- Steve Clamage, TauMetric Corp, steve@taumet.com