It is trivial in C#, but in C++ (native, Win32, Visual C++) I don’t see solution. So, I have class MyClass1 with non-trivial constructor, and in MyClass2 I want to have static member of type MyClass1:
MyClass1.h:
class MyClass1
{
public MyClass1(type1 arg1, type2 arg2);
}
MyClass2.h:
class MyClass2
{
public:
static MyClass1 Field1;
}
And MyClass2.cpp:
MyClass1 MyClass2::Field1(arg1, arg2);
I expect that such code will initialize MyClass2::Field and call MyClass1 constructor during this initialization. However, it looks like compiler allocates memory for Class1 only, and never calls constructor, like if I do this:
MyClass1 MyClass2::Field1 = *(MyClass1 *)malloc(sizeof(MyClass1));
Is there any “official” way in C++ to initialize static class member with nontrivial constructor?
You may be encountering the Static Initialization Order Fiasco. Static variables of class or namespace scope are initialized before
main()is executed, but the order of initialization is dependent on link-time factors.To solve the problem, use the Construct on First Use Idiom, which takes advantage of the fact that function-scope statics are initialized at the time the function is first called.