merlin2011
merlin2011

Reputation: 75585

Are there any guarantees that static initialization will not overwrite the value from explicit initialization?

Suppose I have the following two variables, both statically initialized, and they live in different compilation units.

Foo.cc

Foo foo;

Bar.cc

Bar bar;

Suppose that, ordinarily bar is statically initialized after foo.

If the constructor of foo was written to write the value of bar, is there is a chance that the subsequent static initialization of bar would overwrite the value written by foo?

That is, assuming Bar has a second constructor which takes a string, and the constructor for foo looks like this:

Foo::Foo() {
   bar = Bar("Hello World");
    /// do other stuff to make a Foo
}

Is there any chance that the static initialization for bar will run after foo and overwrite the value of bar written by foo's constructor?

Upvotes: 0

Views: 88

Answers (2)

Amadeus
Amadeus

Reputation: 10665

As Scott Meyers said:

[...] the relative order of initialization of non-local static objects defined in different translation units is undefined. [...]

and:

Fortunately, a small design change eliminates the problem entirely. All that has to be done is to move each non-local static object into its own function, where it's declared static. These functions return references to the objects they contain. Clients then call the functions instead of referring to the objects. In other words, non-local static objects are replaced with local static objects. (Aficionados of design patterns will recognize this as a common implementation of the Singleton pattern.)

As an example of this working can be looked at: http://www.parashift.com/c++-faq/static-init-order-on-first-use-members.html

Upvotes: 0

Collin Dauphinee
Collin Dauphinee

Reputation: 13993

Yes, dynamic initialization (which is what is happening when your static's constructors are invoked) could happen in any order.

If static objects need to depend on each other, it's best practice to dynamically allocate them on demand and protect the initialization so that it happens only once, similar to the singleton pattern.

Upvotes: 1

Related Questions