Thursday, February 16, 2006

The Dangers of Static initialization

As I have mentioned before C++ has a rich set of ways for you too shoot yourself in the foot. And that is what I did today. This time it was because of static initialization. For those familiar with C++, you should know that one can declear variables like this:
static MyClass myVariable;
I am writing a raytracer and this raytracer has a color class. For convenience I added some static variables for commonly used colors.
Color Color::Red(1.0f, 0.0f, 0.0f); Color Color::Green(0.0f, 1.0f, 0.0f); Color Color::Blue(0.0f, 0.0f, 1.0f);
In my code I have a singleton class, AppSettings used to access and store and access settings in the class. I used to create a default scene in my application, so a scene could be rendered when starting the app instead of having to read from file. This scene I was creating in constructor for my main window. For various reasons I decided to move the creation of the default scene to AppSettings. Now suddenly nothing was rendered anymore. I spent a lot of time figuring out what was wrong. Until it hit me that the AppSettings singleton was allocated statically. Using the debugger I discovered the problem: The AppSettings object was constructed before the static color objects. Since my static color objects were used to create the scene they were set to 0.0f, 0.0f, 0.0f when being used by AppSettings. It also occurred to me that I have had this problem before. But I had forgotten about the dangers of static initialization. So my own advice on this is. Avoid using static initialization for complex objects because you never know when the initialization code will actually be executed and in which sequence.

No comments: