简体   繁体   中英

How to initialize static class member with nontrivial constructor?

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.

I would not expect this kind of exception that Vitaliy is getting. Static Initialization Order Fiasco requires two objects where initialization of one object invokes a method on another object.

Here we have a static initializer in MyClass2 that invokes a constructor (not a method) of another class (MyClass1). Of course, we don't need to initialize object before invoking constructor.

In summary, I don't know why Vitaliy is getting this exception. I would be interested to know the answer, but it seems that it is not due to Static Initializer Order Fiasco.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM