Global variables are initialized in order of appearing in the translation module and the relative order of initialization of variables in different translation modules in unspecified (so-called "static initialization order fiasco").
Do namespaces have any influence on that? For example if I have this code:
//first.cpp
int first;
int second;
will it have any difference in initialization order compared to this code:
//second.cpp
namespace {
int first;
}
int second;
Are there cases where putting a global object into a namespace affects initialization order?
The C and C++ standards require that global and static variables that are not explicitly initialized must be set to 0 before program execution. The C/C++ compiler supports preinitialization of uninitialized variables by default.
If the initial value of a static variable can't be evaluated at compile time, the compiler will perform zero-initialization. Hence, during static initialization all static variables are either const-initialized or zero-initialized. After static initialization, dynamic initialization takes place.
Initialization is the process of locating and using the defined values for variable data that is used by a computer program. For example, an operating system or application program is installed with default or user-specified values that determine certain aspects of how the system or program is to function.
The static initialization order fiasco refers to the ambiguity in the order that objects with static storage duration in different translation units are initialized in.
3.6 Other non-local variables with static storage duration have ordered initialization. Variables with ordered initialization defined within a single translation unit shall be initialized in the order of their definitions in the translation unit.
Namespaces have no effect on this - not mentioned in the section.
What does effect the order is different translation units. If you need to define the order across them, use an extension such as GCC's constructor
attribute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With