I.22: Avoid complex initialization of global objects(避免对全局对象进行复杂的初始化)

Reason(原因)

Complex initialization can lead to undefined order of execution.

复杂的初始化可能引起没有定义的执行顺序。

Example(示例)


 

// file1.cextern const X x;const Y y = f(x);   // read x; write y// file2.cextern const Y y;const X x = g(y);   // read y; write x

Since ​​x​​​ and ​​y​​​ are in different translation units the order of calls to ​​f()​​​ and ​​g()​​​ is undefined; one will access an uninitialized ​​const​​. This shows that the order-of-initialization problem for global (namespace scope) objects is not limited to global variables.

由于x和y处于不同的翻译(编译)单位中,因此调用f()和g()的顺序是没有定义的;其中一个会访问没有经过初始化的常量。这表明发生于全局(命名空间范围)对象的初始化顺序问题并不仅限于全局变量。

译者注:也会影响到使用他们的函数。

Note(注意)

Order of initialization problems become particularly difficult to handle in concurrent code. It is usually best to avoid global (namespace scope) objects altogether.

在并发代码中,初始化顺序问题处理起来尤其困难。总而言之,通常情况下的最好的选择是避免全局(命名空间范围)对象。

Enforcement(实施建议)

  • Flag initializers of globals that call non-​​constexpr​​ functions
    标记那些调用非常量表达式函数初始化的全局对象。
    译者注:常量表达式函数可能在编译阶段就可以计算结果,因此安全。
  • Flag initializers of globals that access​​extern​​ objects
    标记那些使用外部变量初始化的的全局对象。
    译者注:外部变量可能以不可预见的方式被初始化。