Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the order of initialization between dependence variables across files?

Tags:

c++

Assume that 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 it guaranteed by the standard that first_string will always be initialized before another_string?

If not, should code like this be avoided in practice?

I tried to figure this out by reading C++ standard N3485 Section 3.6 and 3.7. But I did not find a good answer. My great appreciation if you could point me to section of the standard when you draft the answer. Thank you for your help.

like image 770
taocp Avatar asked Feb 16 '23 10:02

taocp


1 Answers

The order is undefined.

C++ FAQ:

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

That's it. It's that simple.

The tragedy is that you have a 50%-50% chance of dying. If the compilation unit for x.cpp happens to get initialized first, all is well. But if the compilation unit for y.cpp get initialized first, then y's initialization will get run before x's initialization, and you're toast. E.g., y's constructor could call a method on the x object, yet the x object hasn't yet been constructed.

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

like image 128
Elazar Avatar answered Feb 18 '23 23:02

Elazar