I’d have expected the following code to yield a segmentation fault (or otherwise UB):
struct T {
T();
};
T t;
char const* str = "Test string";
T::T() {
std::cout << str; // zero-initialised, only!
}
int main() {}
That’s because t is initialised before str. I’d expect str to hold the value (char const*)0 due to zero-initialisation. My interpretation of [C++11: 3.6.2/2] supports this.
However, the above snippet appears to output the string as expected (and I confirmed the behaviour by also printing the pointer’s value).
Is there some rule of static initialisation that I’m missing here, that allows str to be value-initialised before t begins construction? Where is it in the standard?
This came up on static variable resolution at build time, where an answerer asserted that using char const* rather than std::string for a static global avoids the static initialisation order fiasco. I disagreed, but now I’m not so sure…
I think I found it; what’s happening here is not so much about the built-in type, but about the constant initialiser:
That final sentence would seem to override subsequent sequencing rules, making this ordering apply across Translation Units.