static variables are fully initialized before any function in the same translation block is executed (cpp file more or less). They are not guaranteed to be initialized before main is called if main is in a different translation unit. inline duplicated, where each translation unit has its own copy. This means that inline functions in different translation units than the static variable may try to read / write this variable before it is correctly initialized, which will lead to undefined behavior. (The rules are very complicated, but I remember)
§ 3.6.2 / 4 It is determined by the implementation whether a non-local variable is dynamically initialized with a static storage duration until the first statement of main. If initialization is delayed until some point after the first statement of main, it must occur before the first use of odr (3.2) of any function or variable defined in the same translation unit as the initialized variable.
and
§ 3.2 / 3. A built-in function must be defined in each translation unit in which it is used oddly.
As far as I know, built-in functions
actually no more dangerous than non-built-in functions. Any function that accesses statics in another TU is risky, and since inline simply performs functions in each TU, most of them are unsafe. One way is to use the construct when you first use the idiom .
Implicit specialized templates are complex, but for completeness:
§ 14.7.1 / 3 [temp.inst] initialization (and any side effects associated with it) of a static data member does not occur if the static data member itself is not used in a way that requires the definition of a static data member exists.
Thus, static members of template classes are always initialized before use.
All of the above falls under the static initialization order fiasco ), which the aforementioned "construction upon first use of idom" solves.
source share