I am writing a raytracer and this raytracer has a color class. For convenience I added some static variables for commonly used colors.static MyClass myVariable;
In my code I have a singleton class,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);
AppSettingsused 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
AppSettingssingleton was allocated statically. Using the debugger I discovered the problem: The
AppSettingsobject 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.0fwhen 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.