The code below is in the same translation unit and A::v
is defined after x
, why A::v
is not initialized to "ok" ?
#include <string>
#include <iostream>
std::string foo() {
return "OK";
}
std::string x = foo();
struct A {
static inline std::string v = x;
};
int main() {
std::cout << A::v << std::endl; // didn't print "OK", why?
}
Per [basic.start.dynamic]/1, a non-inline non-templated non-block variable with static storage duration has "ordered" initialization, while an inline non-templated non-block variable with static storage duration has "partially ordered" initialization.
Per [basic.start.dynamic]/3, we only have an initialization order guarantee between two non-block variables with static storage duration when:
Therefore, if the non-inline variable is defined before the inline variable, we don't have an initialization order guarantee. We only have an initialization order guarantee when the inline variable is first. So in this code, v
can be initialized before x
, resulting in undefined behaviour.