Following code
#include <iostream>
struct A {
A() {
std::cout << std::endl;
}
};
struct B {
static inline A a;
};
int main() {
}
succeeds after compiling with gcc, but crashes with segmentation fault after compiling with clang. Is the code not standard or is clang wrong?
Cppreference on
std::ios_base::Initreads:You do include
<iostream>beforeB::a, but the initialization ofB::a(withB::abeingstatic inlinevariable) is not part of ordered initialization, so it can be initialized beforestd::ios_base::Init. It seems that Clang (some versions, at least) does exactly this. This is a valid behaviour.The standard reads ([basic.start.dynamic]):
So, an initialization of instance of
std::ios_base::Initis ordered, and initialization ofB::ais partially-ordered.3.1 and 3.2 don't apply. So we have indeterminately sequenced initializations.
You can make
B::aa non-inlinestatic variable or somehow forcestd::ios_base::Initinitialization before usingstd::cout, for example: