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

前端 未结 2 869
执笔经年
执笔经年 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:32

    The order of initialization of global objects is defined only within one translation unit. Between different translation the order isn't guaranteed. Thus, you probably see behavior resulting from the std::unordered_map being accessed before it is constructed.

    The way to avoid these problems is to not use global objects, of course. If you realky need to use a global object it is best to wrap the object by a function. This way it is guaranteed that the object is constructed the first time it is accessed. With C++ 2011 the construction is even thread-safe:

    T& global() {
        static T rc;
        return rc;
    }
    

提交回复
热议问题