sharptooth
sharptooth

Reputation: 170509

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?

Upvotes: 12

Views: 1720

Answers (2)

Jan Hudec
Jan Hudec

Reputation: 76316

Well, the "Global variables are initialized in order of appearing in the translation module" is definite. It does not leave any room for anything else, like namespaces, to affect the order.

Actually, "Global variables are initialized in order ..." is imprecise quotation of the standard as is formally wrong. The exact wording from C++ Standard, ISO/IEC 14882:2003, 3.6.2 paragraph 1 is:

Objects with static storage duration defined in namespace scope in the same translation unit and dynamically initialized shall be initialized in the order in which their definition appears in the translation unit.

So rather than "global" it says "with static storage", that is all non-local variables whether they are global, namespace members or class members and whether they are declared static or not.

Also it adds "and dynamically initialized". Variables with trivial constructors and constant initializer are always initialized first (by simply loading their values from the binary) and than all non-constant initializers are evaluated and non-trivial constructors are run in that order. This is important, so you can for example reliably create a linked list in those constructors; if it's head is plain pointer, it is already initialized, so you can safely work with it.

Upvotes: 5

Pubby
Pubby

Reputation: 53067

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.

Upvotes: 11

Related Questions