iVoid
iVoid

Reputation: 721

Is initialization of static member of a class guaranteed before initialization of a static object of that class?

I encountered this C++ static initialization order related query at a code review recently.

  1. I've a class with static member variable in a compilation unit
  2. 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.

Upvotes: 11

Views: 492

Answers (1)

R Sahu
R Sahu

Reputation: 206667

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.

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.

  1. All variables are zero-initialized (order not specified). This is called zero initialization.
  2. All variables that can be initialized using constant values are initialized. This is called constant initialization.

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

Related Questions