C ++ static initialization order: add to map

We cannot determine the initialization order of static objects.

But is this a problem in the following example?

  • one static variable is a map (or another container)
  • from another static variable we populate this 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 will not depend on the order in the container. But what about the first add to the container? Can I be sure that he initialized "enough" to take the first element?

Or is this another issue of the "static initialization fiasco order"?

+4
source share
3 answers

To be lazy, here is a copy of http://en.cppreference.com/ :

Nonlocal variables

, ( , . ).

...

:

...

, - ( ) ( ) .

- main/thread, odr-use / , , , .

odr-use:

, odr, ( ) , ;

s_map Factory::Register, .


, / .

, Factory::Register, .

, , Factory::Register , .

+3

. .

- () , :

h :

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

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

cpp:

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

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

, . . , " " : / .

+2

Staticity is initialized before first use. You must be fine.

edit: As indicated, does not apply to multiple translation units.

0
source

Source: https://habr.com/ru/post/1693058/


All Articles