简体   繁体   English

如何用非平凡的构造函数初始化静态类成员?

[英]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. 它在C#中是微不足道的,但在C ++(native,Win32,Visual C ++)中我没有看到解决方案。 So, I have class MyClass1 with non-trivial constructor, and in MyClass2 I want to have static member of type MyClass1: 所以,我有MyClass1类和非平凡的构造函数,而在MyClass2中我想拥有MyClass1类型的静态成员:

MyClass1.h: MyClass1.h:

class MyClass1 
{
   public MyClass1(type1 arg1, type2 arg2);
}

MyClass2.h: MyClass2.h:

class MyClass2
{
public:
   static MyClass1 Field1;
}

And MyClass2.cpp: 和MyClass2.cpp:

MyClass1 MyClass2::Field1(arg1, arg2);

I expect that such code will initialize MyClass2::Field and call MyClass1 constructor during this initialization. 我希望这样的代码将初始化MyClass2 :: Field并在初始化期间调用MyClass1构造函数。 However, it looks like compiler allocates memory for Class1 only, and never calls constructor, like if I do this: 但是,看起来编译器只为Class1分配内存,而且从不调用构造函数,就像我这样做:

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

Is there any "official" way in C++ to initialize static class member with nontrivial constructor? 在C ++中是否有任何“官方”方式来初始化具有非平凡构造函数的静态类成员?

You may be encountering the Static Initialization Order Fiasco . 您可能会遇到静态初始化订单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. 类或命名空间作用域的静态变量在执行main()之前初始化,但初始化顺序取决于链接时间因素。

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. 要解决这个问题,请使用Construct on First Use Idiom ,它利用了在首次调用函数时初始化函数范围静态的事实。

I would not expect this kind of exception that Vitaliy is getting. 我不希望Vitaliy得到这种例外。 Static Initialization Order Fiasco requires two objects where initialization of one object invokes a method on another object. 静态初始化顺序Fiasco需要两个对象,其中一个对象的初始化调用另一个对象上的方法

Here we have a static initializer in MyClass2 that invokes a constructor (not a method) of another class (MyClass1). 这里我们在MyClass2中有一个静态初始化程序,它调用另一个类(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. 总之,我不知道为什么Vitaliy会得到这个例外。 I would be interested to know the answer, but it seems that it is not due to Static Initializer Order Fiasco. 我很想知道答案,但似乎不是由于静态初始化程序订单Fiasco。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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