static unordered_map is erased when putting into different compilation unit in XCode

前端 未结 2 908
执笔经年
执笔经年 2021-01-24 10:55

I have a static unordered_map in my class C. I experience difference in behaviour if I put my class definition and declaration in different files from the file containing functi

2条回答
  •  半阙折子戏
    2021-01-24 11:33

    Thanks, guys! Following Dietmar's advice, I did this:

    class C{
    //...
    private:
      static unordered_map& m();
    };
    
    unordered_map& C::m()
    {
      static unordered_map m;
      return m;
    }
    

    and then I kept referring to m(). It is strange that it did not happen before. I guess I got lucky. But then, this should be a case for a warning message, shouldn't it?


    To avoid mistakes like this I will use the following macros to declare and define static variables:

    /// Use this macro in classes to declare static variables
    #define DECLARE_STATIC(type, name) static type& name();
    
    /// Use this macro in definition files to define static variables
    #define DEFINE_STATIC(type, name) type& name(){static type local; return local;}
    

    Usage in this case:

    class C{
    //...
    private:
      DECLARE_STATIC(unordered_map, m);
    }
    DEFINE_STATIC(unordered_map, m)
    

提交回复
热议问题