Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do namespaces affect initialization order in C++?

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?

like image 705
sharptooth Avatar asked Dec 02 '11 08:12

sharptooth


People also ask

Does C initialize variables to zero?

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.

What controls the initial value of the non initialized static variables?

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.

What is initialization in C?

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.

What is static initialization order fiasco?

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.


1 Answers

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.

like image 193
Pubby Avatar answered Sep 20 '22 14:09

Pubby