简体   繁体   中英

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

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. 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

This means that an implementation is not required to initialize our object before main() even though all compilers I know do that. 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:

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?

Technically? Yes , per the quote you provided and the definition of 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. 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 . I realise that's an anti-pattern.

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