merlin2011
merlin2011

Reputation: 75585

Is it possible to check whether a static variable has been initialized yet in C++?

Based on the answer to this question C++ static initialization order, it seems impossible to control the order of static initialization directly. However, suppose I were to explicit initialize static variables inside the constructor for a statically initialized object foo which depended on a different global object bar. Is there a way for the constructor of foo, on invocation, to determine whether bar had already been initialized statically?

That is, suppose I have in one compilation unit.

Foo::Foo() {
// Can I check here whether bar has already been initialized?

// do something that needs bar to be initialized
// If bar has not been initialized, then I will crash and burn.
}

// statically initialized foo
Foo foo;

In a different compilation unit:

Bar bar;

The goal is to make sure that bar is initialized before the (statically invoked) constructor for foo runs to the point where it needs bar. We could explicitly initiate bar in the constructor of foo, but we need to know whether bar has already been initialized.

Upvotes: 1

Views: 2203

Answers (1)

Glenn Teitelbaum
Glenn Teitelbaum

Reputation: 10343

No it is not possible, but if you want to see how to implement something that is always initialized before use, look at the implementation of std::cout

Upvotes: 2

Related Questions