Reputation: 177
The question pretty much like in the topic, I couldn’t find clear answer to this as almost every example covers two namespace scope instances depending on each other. An example:
a.hpp
class MyGlobal {/*definition*/};
extern const MyGlobal global;
a.cpp
const MyGlobal global;
b.hpp
void myFunc();
b.cpp
extern const MyGlobal global;
class MyLocalStatic
{
public:
MyLocalStatic() { /* do something with global */ }
};
void myFunc()
{
static MyLocalStatic s;
}
main.cpp
int main() { myFunc(); }
Let’s say that both MyGlobal
and MyStaticLocal
have some non-trivial constructors and so are initialized during dynamic initialization.
I know that compiler can defer dynamic initialization until the variable actually used. But what if it’s not used in the same TU at all? When will compiler decide to initialize it?
Another question: if global
is constant initialized I assume there’s no problem. But is it possible that s
is also constant initialized (and still depends on global
somehow) or this is not possible?
Would be grateful for some quotes from the standard :)
Upvotes: 1
Views: 260
Reputation: 96012
Function-local static
variables are created when control reaches their declaration for the first time. In your case it'll happen after entering main
, at which point global
is surely initialized.
is it possible that
s
is also constant initialized
Yes.
...and still depends on
global
somehow
Yes, only if global
is constexpr
.
If a variable is constant-initialized, there's nothing to worry about. There's no static-init-order fiasco at compile-time.
Upvotes: 2