12

We cannot determine the order of the initialization of static objects.

But is this a problem in the following example?

  • one static variable is a map (or other container)
  • from other static variable we populate that map

the code:

class Factory
{
public:
    static bool Register(name, func);

private:
    static map<string, func> s_map;
};

// in cpp file
map<string, func> Factory::s_map;

bool Factory::Register(name, func)
{
    s_map[name] = func;
}

and in another cpp file

static bool registered = Factory::Register("myType", MyTypeCreate);

When I register more types I don't depend on the order in the container. But what about the first addition to the container? Can I be sure it's initialized "enough" to take the first element?

Or it's another problem of "static initialization order fiasco"?

2 Answers 2

9

Your scenario is not guaranteed to work as expected. The success depends on the link order.

One approach to be sure is to access the map through a (static) function that creates the object as a static variable like this:

h file:

class Factory
{
public:
    static void Register(string, func);

private:
    static map<string, func>& TheMap();
};

cpp file:

map<string, func>& Factory::TheMap()
{
    static map<string, func> g_;
    return g_;
}

void Factory::Register(string name, func f)
{
    TheMap()[name] = f;
}

The downside of this is that the order of destruction of static variables is hard to control by you as the developer. In the case of the map this is no problem. But if static variables reference each other, the "static linking fiasco" gets even worse: In my experience it's much harder to prevent/debug a crash when a program ends compared to when it starts.


Edit, 2022-09-01: I fixed issues in code (taken from the question). Now it would compile in the right context (not included here).

6
  • so it works when I'm in one translation unit but might fail when the static vars are spread over several units. Sounds logical.
    – fen
    Feb 2, 2018 at 8:15
  • so when you access such map through a static function then we guarantee it's created before the first use.
    – fen
    Feb 2, 2018 at 8:17
  • @fen I think it works over different compilation units. Of course your registered variable would be a problem, if it wouldn't be static but with extern linkage ...
    – Wolf
    Feb 2, 2018 at 8:22
  • 3
    "the order of destruction of static variables is not defined.": It is: reverse order of creation.
    – Jarod42
    Feb 2, 2018 at 8:35
  • 1
    @Jarod42 Well, I over-simplified this. The problem is that it's hard to control it when the initialization order depends on actual runtime properties. I rephrased that.
    – Wolf
    Feb 2, 2018 at 8:40
6

Being lazy, here's a copy from http://en.cppreference.com/:

Non-local variables

All non-local variables with static storage duration are initialized as part of program startup, before the execution of the main function begins (unless deferred, see below).

...

Dynamic initialization

After all static initialization is completed, dynamic initialization of non-local variables occurs in the following situations:

...

Deferred dynamic initialization

It is implementation-defined whether dynamic initialization happens-before the first statement of the main function (for statics) or the initial function of the thread (for thread-locals), or deferred to happen after.

If the initialization of a non-inline variable is deferred to happen after the first statement of main/thread function, it happens before the first odr-use of any variable with static/thread storage duration defined in the same translation unit as the variable to be initialized.

The important part is odr-use:

ODR-use

Informally, an object is odr-used if its value is read (unless it is a compile time constant) or written, its address is taken, or a reference is bound to it;

Since the s_map is populated through Factory::Register, I don't see a problem here.


If the map implementation is very trivial, it may even be initialized as part of the static initialization/at compile time.

But even if the initialization is deferred, it will be initialized before the use in Factory::Register, as long as both are in the same translation unit.

However, if the map is defined in one translation unit, and Factory::Register is defined in another, anything can happen.

8
  • so the map is always initialized first - as it's the part of static initialization (zero initialization). Then s_registered is part of dynamic initialization (it calls a method) - so it will work fine.... is that correct?
    – fen
    Feb 2, 2018 at 8:29
  • @fen: You will have issue if you split Factory::s_map and Factory::Register definition in different TU.
    – Jarod42
    Feb 2, 2018 at 8:37
  • 1
    @fen it seems like the map may be initialized before the first register call, but it depends on if the compiler supports the distinction. As far as I see, it's possible to use a map implementation that has no inline constructor, how sould the compiler decide if it's trivially initialized? I find this reference hard to keep in mind and have to deal with compilers that are not even C++11 compliant, so I even try to avoid to be forced to used the singleton approach shown in my answer.
    – Wolf
    Feb 2, 2018 at 8:37
  • 1
    @fen if you declare an object of a class with a default constructor, it will exactly look like the zero-initialization of a language-level type like int. But in fact it may involve several non-trivial calls. If the constructor is declared inline and its implementation is trivial (zero or constant initialization), the compiler will mostly understand that.
    – Wolf
    Feb 2, 2018 at 8:49
  • 1
    I tried this approach but I got an seg fault. The call to Register was in 1 cpp file and the map was defined in another cpp file. As far as I could tell from the debugger, the call to assign s_registered happened before the 'trivial' initialization of the map. I used Wolf's approach below where I had a function called GetMap. This ensured the static map was created at first use.
    – tree
    Jul 4, 2019 at 16:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.