简体   繁体   English

静态成员函数初始化静态成员变量 - 用法和风险?

[英]Static member function to initialize static member variable - usage and risks?

In the case of In MyClass.h 在In MyClass.h中

class MyClass 
{
    static vector<type> types;
    static vector<type> createTypes();
}

In MyClass.cpp 在MyClass.cpp中

vector<type> MyClass::types = createTypes();

MyClass::MyClass()
{
}

When will be createTypes() executed and does this method of initializing a static variable involve any risks? 什么时候执行createTypes()并且这种初始化静态变量的方法是否涉及任何风险?

The function will be called along with other static initializers, before main() starts. main()启动之前,该函数将与其他静态初始化程序一起调用。 You don't risk anything more than with other means of static initialization. 除了使用其他静态初始化方法之外,您不会冒任何风险。

Keep in mind tough that all static initializers should be designed to avoid triggering a SIOF -- Static Initialization Order Fiasco. 请记住,所有静态初始化器都应设计成避免触发SIOF - 静态初始化命令Fiasco。

Static initializers in the same translation unit are executed in the order of their declaration in the file. 同一翻译单元中的静态初始化程序按其在文件中声明的顺序执行。 However, initialization order across multiple translation units is not defined. 然而,在多个翻译单元初始化顺序没有定义。 A SIOF arises when a static initializer depends on another, which is in another translation unit. 当静态初始化程序依赖于另一个转换单元时,SIOF就会出现。

Then, depending on the phase of the Moon, either both objects will initialize in the right order and everything will work, or they will initialize in the opposite order and you'll use a not-yet-constructed object -- Undefined behaviour ensues. 然后,根据月亮的相位,要么两个对象都将以正确的顺序初始化并且一切都会起作用,或者它们将以相反的顺序初始化并且您将使用尚未构造的对象 - 接着会出现未定义的行为。

The SIOF-guard pattern avoids this by replacing static variables like the following : SIOF-guard模式通过替换如下的静态变量来避免这种情况:

std::list<Foo> gFoos;

... with a function that contains the variable as a local static : ...使用包含变量作为本地静态的函数:

std::list<Foo> &gFoos() {
    static std::list<Foo> theList;
    return theList;
}

This way, the variable is always initialized on the first call of the function, and it's impossible to access it before its construction. 这样,变量总是在函数的第一次调用时初始化,并且在构造之前无法访问它。

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

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