How to initialize a static member of a class with a non-trivial constructor?

This is trivial in C #, but in C ++ (native, Win32, Visual C ++) I don't see a solution. So, I have a class MyClass1 with a non-trivial constructor, and in MyClass2 I want to have a static member like 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 this code to initialize MyClass2 :: Field and call the constructor MyClass1 during this initialization. However, it seems that the compiler allocates memory only for class 1 and never calls the constructor, for example, if I do this:

 MyClass1 MyClass2::Field1 = *(MyClass1 *)malloc(sizeof(MyClass1)); 

Is there any โ€œofficialโ€ way in C ++ to initialize a static member of a class with a non-trivial constructor?

+4
source share
2 answers

You might be faced with the Fiasco Static Initialization Order . Static class or namespace variables are initialized before main() executed, but the order of initialization depends on the link time factors.

To solve this problem, use Construct on First Use Idiom , which uses the fact that the statics of a function-object is initialized for the time when the function is first called.

+6
source

I would not expect such an exception that Vitaly gets. The Fiasco static initialization order requires two objects, where the initialization of one object calls a method for another object.

Here we have a static initializer in MyClass2 that calls the constructor (and not the method) of another class (MyClass1). Of course, we do not need to initialize the object before calling the constructor.

So, I do not know why Vitaly gets this exception. I would be interested to know the answer, but it seems that this is not due to the Fiasco Static Initializer Order.

0
source