Reputation: 721
I encountered this C++ static initialization order related query at a code review recently.
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
.
Upvotes: 11
Views: 492
Reputation: 206667
In the code, would
mFunc
be initialized tonullptr
beforemyClassObj
gets created? The reason for the query is that if the order is not guaranteed, thenmFunc
may get initialized again tonullptr
.
The answer to the question is "Yes".
Setting aside the issue of initialization of thread specific objects, initialization of non-local variables is carried out in the following order.
Those ( 1 and 2 above) are called static initialization.
After that, dynamic initialization is performed.
In your case, MyClass::mFunc
is initialized using constant initialization while myClassObj
is initialized using dynamic initialization. Hence, the former is guaranteed to be initialized first.
More on this topic can be found at https://timsong-cpp.github.io/cppwp/n3337/basic.start.init.
Upvotes: 6