Reputation: 13886
Just wondering if in the following the static members are initialised before the Foo class object is initialised. Since both are static variables, one a static member and the other a static global variable, initialisation order is not guaranteed or specified.
struct Foo
{
Foo() { assert(a == 7); }
static inline int a = 7;
};
Foo foo;
int main()
{
}
So the initialisation order between the global Foo and the static class member is not defined, you would think there is no guarantee. However, I'm thinking that before a Foo is instantiated that the Foo class would need to be completed/initialised first, and so in that case that there might be a guarantee that the static member variable would be initialised first.
Upvotes: 0
Views: 53
Reputation: 76628
I'm thinking that before a Foo is instantiated that the Foo class would need to be completed/initialised first
That is not generally the case, so you should be careful with that assumption.
However, in your specific example, the order of initialization is guaranteed. The initializer of a
is a constant expression and therefore a
will be constant-initialized. Constant-initialization is guaranteed to happen before any dynamic initialization, which the initialization of foo
is.
Even if a
was not constant-initialized, there wouldn't be an issue here, because foo
is defined after a
in the same translation unit, foo
is not an inline or template variable and because Foo
is not a template. If either of these requirements were not fulfilled, there could be problems in the ordering guarantees.
Upvotes: 2