I encountered this C++ static initialization order related query at a code review recently.
- I've a class with static member variable in a compilation unit
- I've a static object of that class using a constructor in a different compilation unit
Here, I want to know if the static member variable is guaranteed to be initialized before the static object constructor is called?
MyClass.h:
typedef int (*MyFunc)(int);
class MyClass {
MyClass(MyFunc fptr) {
mFunc = fptr;
}
static MyFunc mFunc;
}
MyClass.cpp:
MyFunc MyClass::mFunc = nullptr;
MyDifferentClass.h:
MyDifferentClass {
public:
static int MyStaticFunc(int);
}
MyDifferentClass.cpp:
static MyClass myClassObj(MyDifferentClass::MyStaticFunc);
In the code, would mFunc
be initialized to nullptr
before myClassObj
gets created? The reason for the query is that if the order is not guaranteed, then mFunc
may get initialized again to nullptr
.