Unused global static initializers

If I have an internally linked global that is never used, is its initializer guaranteed to work? For example:

static int x = SideEffectfulFunction();

      

or

namespace {
    int x = SideEffectfulFunction();
}

      

Is it SideEffectfulFunction()

guaranteed to be called even if x

never referenced? Or is deletion allowed x

?

+3


source to share


2 answers


Yes, the standard guarantees it

Static storage duration [basic.stc.static]



2 If a variable with static storage duration has an initialization or destructor with side effects, it should not be disposed of, even if not used, except that the class object or its copy / move can be disposed of, as stated in 15.8.

+9


source


Launch is guaranteed. If you create multiple static objects that reference each other in different source files, there is no guarantee in which order the objects are initialized, this is called static initialization order fiasco

, in which case you can create a function that creates a static object ensuring that the initialization order is first is a function object and then a secondary object.



Source: https://isocpp.org/wiki/faq/ctors#static-init-order

0


source







All Articles