Static data element in a static member of a C ++ class function to initialize

I have a macro that I use to add a key, a value for a registry card. (Suppose AddToMap is located on a global static object that is defined elsewhere.) The AddKey macro is called in different places in the code after defining different classes (some kind of registry for classes). The code is split into many .h and .cc files with complex dependencies.

I have the following code snippet that works:

#define AddKey(key, val)\
namespace NSP_##key {\
class A {\
    public:\
        static bool foo() {\
        static bool dummy = AddToMap(#key, #val);\
}\
};\
static bool dummy_A = A::foo();\
}

`

I want to know how a static variable layout is created and initialized. When I use GDB, I see that this A :: add is called well before main, or anything else if called. This is expected from static variables.

, , , " "

#define AddKey(key, val)\
namespace NS_##key {\
    static bool A_foo() {\
    static bool dummy = AddToMap(#key, #val);\
}\
static bool dummy_A = A_foo();\
}

, dummy_A - ++ A_foo(). dummy vs, ?

+4
1

static , , . , AddKey(MyClass, hello), NSP_MyClass::A::foo(), AddToMap.

static , , , . , *.cc NS_MyClass::A_foo(), AddKey(MyClass, hello). AddToMap , .

inline static, , :

#define AddKey(key, val)\
namespace NS_##key {\
    inline bool A_foo() {\
        static bool dummy = AddToMap(#key, #val);\
    }\
    static bool dummy_A = A_foo();\
}
+1

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


All Articles