简体   繁体   中英

Static variable initialization - clarification

I have a static variable of a class in another class.

class1.h

class1
{
public:
static class2 check;
}

class2.cpp
class2 class1::check;

Now class2.cpp has the following default constructor

class2()
{
  size = G_SIZE; //this G_SIZE is an extern variable, which gets initialized after main() is called.
}

Since the static initialization happens before the extern variable is initialized, I get 0 initialized to size. How do I handle this?

EDIT : Not sure why it is being downvoted.

You should never have static variables depend on other variables (especially other static variables). But that is exactly what you are doing.

The first recommendation: Don't do it. Find a better design.

The next recommendation: if you must do it (and in this case, most certainly you do not), you can wrap your access in a function, which will delay until runtime, when the values are guaranteed to be setup. See here: What is the lifetime of a static variable in a C++ function? and here: C++ static initialization order

By telling compiler 'static' - you will most probably get that variable initialized during mainCRTstartup - that's before main is called. If you're performing variable initialization during main, other data initialization must happen after that - you could have doInitialize() like function call, which would perform initialization of your 'check' variable.

It's also possible to have static written inside function itself - then static gets initialized when that function gets called - you could place 'static' after you initialize G_SIZE in main itself.

Playing around with order or constructors / destructors is always bit of luck game (Dangerous) - order to constructors and destructors is not guaranteed, and it's possible that you'll hit uninitialized data when initializing in static - simply because another variable was not initialized yet.

But sometimes even destructor call order might needs to be altered. -

FYI:
http://www.codeproject.com/Articles/442784/Best-gotchas-of-Cplusplus-CLI
CrtDestroyStatics.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM