What is the initialization order between dependency variables between files?

Suppose I have the following code:

extern std::string first_string; //defined in another file std::string another_string(first_string + "some other string"); 

My question is:

Is this guaranteed by the standard that first_string will always be initialized before another_string ?

If not, should such codes be avoided in practice?

I tried to figure this out by reading the C ++ N3485 standard of sections 3.6 and 3.7. But I did not find a good answer. My big recognition is if you can point me to the section of the standard when you draw the answer. Thank you for your help.

+4
source share
2 answers

The order is undefined.

C ++ Frequently Asked Questions :

suppose you have two static objects x and y that exist in separate source files, say x.cpp and y.cpp. Suppose further that initialization for the object y (usually the constructor of the object y) calls some method for the object x.

What is it. It's simple.

The tragedy is that you have a 50% -50% chance of dying. If the compilation block for x.cpp is initialized first, that's it. But if you first initialize the compilation unit for y.cpp, then the initialization of y will be started before the initialization of x and the output. For example, the y constructor may call a method on an x ​​object, but the x object has not yet been created.

and see How to prevent the "static initialization order fiasco"? .

+5
source

It is undefined; Wed What is a "static order order fiasco"? . The relevant part of the Standard is §3.6.2 “Initialization of non-local variables”, which states that

Otherwise, the variable initialization is indefinitely sequenced relative to the variable initialization defined in another translation unit.

+3
source

Source: https://habr.com/ru/post/1483057/


All Articles