Xref: utzoo comp.lang.c++:8999 gnu.g++.bug:2148 gnu.g++.lib.bug:386 Path: utzoo!attcan!uunet!decwrl!ucbvax!galileo.berkeley.edu!jbuck From: jbuck@galileo.berkeley.edu (Joe Buck) Newsgroups: comp.lang.c++,gnu.g++.bug,gnu.g++.lib.bug Subject: problems with calling streams from constructors Message-ID: <38170@ucbvax.BERKELEY.EDU> Date: 15 Aug 90 19:28:49 GMT Sender: usenet@ucbvax.BERKELEY.EDU Lines: 38 With g++ (1.37.1) and libg++ (1.37.0) the following code results in a fatal error when the MyClass constructor is called for globalObj: class MyClass { int i; public: MyClass(); // other stuff here } MyClass::MyClass () { cerr << "Calling constructor for MyClass\n"; i = 0; } MyClass globalObj; The error occurs because global objects are initialized in the order that object modules are handed to the linker, and cerr is not yet initialized when the constructor for globalObj is called. As a result, the ostream::operator<<(whatever) function dereferences null pointers. I know I can work around this problem by searching libg++ twice; I also have a workaround that causes gnulib3.c to call the constructors in reverse order. Reverse order always works when everything but main() is obtained from a library and there are no circular dependencies. Still, it's an inelegant hack. Ellis and Stroustrup (p. 21) discuss this problem and imply that this problem has been solved for the iostream library. Can anyone discuss how this is done? I have similar problems in other code. If there is a standard fix, could it be implemented in libg++? I hate having to avoid streams because a function may be called by a constructor. -- Joe Buck jbuck@galileo.berkeley.edu {uunet,ucbvax}!galileo.berkeley.edu!jbuck