简体   繁体   English

C ++静态存储持续时间对象在main()之前初始化

[英]C++ Static storage duration objects initialization before main()

Suppose we have some global object subjected to dynamic initialization: 假设我们有一些全局对象进行动态初始化:

class A {
    A() { std::cout << "constructor\n"; }
};
A global_a; // Here it is

// Other translation unit
int main()
{
    return 0;
}
C++14 §3.6.2 clause 4 C ++14§3.6.2第4条

It is implementation-defined whether the dynamic initialization of a non-local variable with static storage duration is done before the first statement of main. 实现定义是否在第一个main语句之前完成具有静态存储持续时间的非局部变量的动态初始化。 If the initialization is deferred to some point in time after the first statement of main, it shall occur before the first odr-use (3.2) of any function or variable defined in the same translation unit as the variable to be initialized 如果初始化延迟到第一个main语句之后的某个时间点,它应该在与要初始化的变量相同的转换单元中定义的任何函数或变量的第一个odr-use(3.2)之前发生。

This means that an implementation is not required to initialize our object before main() even though all compilers I know do that. 这意味着在main()之前初始化对象不需要实现,即使我知道的所有编译器都这样做。 This is unfortunate since sometimes it is very convenient to have such guarantee, eg for independent self-registering factories residing in a separate file, etc. 这是不幸的,因为有时这种保证是非常方便的,例如对于居住在单独文件中的独立自注册工厂等。

So I came up with the following: what if we define some inline function: 所以我想出了以下内容:如果我们定义一些内联函数怎么办:

inline void f(){}

in every translation unit (supposedly using a common header). 在每个翻译单元(假设使用共同的标题)。 Then in the beggining of main() we odr-use it in some way: 然后在main()的开始中,我们以某种方式使用它:

int main()
{
    f();
    //...
}

Will this guarantee that all the translation units which provide a definition for f() will have their global objects initialized at this point? 这是否可以保证为f()提供定义的所有翻译单元都会在此时初始化其全局对象?

Technically? 技术上? Yes , per the quote you provided and the definition of odr-use . 是的 ,根据您提供的报价和odr-use的定义。

In practice I'm not sure I'd rely on it. 在实践中,我不确定我会依赖它。 I can well imagine compilers optimising f() away and having some bug that then ruins what you're trying to rely on. 我可以想象编译器优化f()并有一些bug然后破坏你想要依赖的东西。 Though I have no data to support this; 虽然我没有数据支持这个; it just seems like a prime candidate for non-compliance, based on experience. 根据经验,它似乎只是不合规的主要候选人。

If you want to really, really ensure that something happens when your program starts up, on balance it might be better to invoke some "initialisation" function on global_a at the top of main . 如果你想真的,真的确保有事时你的程序启动时,在平衡可能会更好援引一些“初始化”功能global_a在顶部main I realise that's an anti-pattern. 我意识到这是一种反模式。

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

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