Static object constructors

Don't rely on static objects in other files being available in functions called at static constructor time. C++ guarantees that, within a file, static objects are constructed in order from the top of the file to the bottom. But the order of execution isn't guaranteed between files. If, in the course of executing the constructor for a static object, you make reference to another static object (directly or indirectly, through a function call), the chances are 50-50 that the other static object's constructor hasn't executed yet, and the reference will fail.

It's not clear that this problem can be overcome, especially in the context of shared libraries. To solve it, the shared library loader must be able to deduce the dependency between static objects, which is almost impossible considering that dependencies can arise after multiple levels of indirect function calls--especially virtual functions calls whose targets cannot be known at load time.

Because you can't count on things to work at static constructor time unless they are specifically documented to do so--and most should not make that promise--avoid exporting static objects as part of an interface that can be called from static object constructors (this is also important for performance reasons, as described earlier). For more information, see "Avoid static objects" on page 86.

NOTE The Annotated C++ Reference Manual (Stroustrup) discusses a technique (not based on static objects) that achieves much of the same benefit as static objects but doesn't suffer from this problem. Read xa4 3.4, "Start and Termination," if you are thinking about exporting static objects to clients.

[Contents] [Previous] [Next]
Click the icon to mail questions or corrections about this material to Taligent personnel.
Copyright©1995 Taligent,Inc. All rights reserved.

Generated with WebMaker