3 ms·
I just saw someone use a globally constructed object to instantiate some global variables and it seemed like a neat solution, but I don't really know C++. What
by krichman 13y ago
I just saw someone use a globally constructed object to instantiate some global variables and it seemed like a neat solution, but I don't really know C++. What causes it to go wrong?
- malkia 13y agoIt depends on compiler / librarian / linker. I'm talking from experience here, not from deep knowledge or understanding the problem. So basically what happens, is that if you have a lone variable globally instantiated, but no one refers to it, it might be stripped from the final linking, and as such any constructors/destructors associated with it would not be called. Now if you are linking directly to the .obj file where the variable is declared it most likely would be put into account, but if the .obj is in a .lib (.a) then it might not. Again, do some experiments, try it out. There is another nastiness with globally initialized variables, that one should not expet some kind of order when the things are initialized. We've had code in the past (Dreamcast) where globally initialized variables, which were assigned the values of other globally initialized variables and then some operation on them would not always work: e.g. this at the top level: float x = 10; float y = x + 20; It worked most of the time, and then if someone started moving variables to other object files, it stopped. Check the http://yosefk.com/c++fqa/ http://yosefk.com/c++fqa/ for more gotchas.