c++ static initialization question

Young, Michael Michael.Young@paetec.com
Fri Mar 5 23:35:00 GMT 2010


> The problem
> -----------
> In short I have a class "Logger". In its constructor are initialized some static pointers.
>  1) first a static Logger object start constructing.
>  2) In the midle of the constructor, another static Logger object from another
>     translation unit start its constructor
>  3) It enters for second time in the initialization of the same static pointers before the
>     first initialization finished.
> 
> My question is. Where can I search for information about static initialization in order to avoid this? How can I modify my code?

This really isn't a gcc compiler issue - it's a general "how-to-do-X in C++" question; you'd likely be better served via a different mailing list / forum.

Having said that, here's some direction and things to look at - 

If I understand correctly, the ctor of one Logger explicity calls the ctor of another Logger (i.e., not via base class initialization).  That seems a bit odd to me, so you may want to look at your architecture and see if it really makes sense, or if you can rework it to avoid this problem.  One option is to construct one Logger fully, and then construct the second one, passing it the first as a ctor parameter so the new (second) logger can associate and use it.  Otherwise, maybe you somehow want to mark that the initialization of the static pointer(s) is already in progress ("atomic" - from a stmt, not CPU instruction, level - assignment of a ptr)?  This is how singletons I've seen are often implemented.

Regarding static object initialization order - there's something called a "Schwarz Counter" idiom (I think it was in an issue of C++ report and/or C++ Gems book) that you should take a look at... I believe the article's author was Jerry Schwarz.  Anyway, you should be able to search on the internet and find something on it.

  - Michael



More information about the Gcc-help mailing list