我有一个类,其中包含一个std::map静态成员。我在同一翻译单元(即相同的cpp文件)中在构造函数体实现之前初始化它。但是我的程序没有输出结果。我发现了静态初始化顺序灾难的问题,但我不认为这可能是原因。
class Test {
public:
static std::map<std::string, Test*> a;
Test(std::string ID) {
/* in my complete code (where constructor
* implementation and map initialization
* are in a separate Test.cpp file), this fails, maybe
* because the map is not initialized at the time
* the constructor is being called by a sub class of Test */
a.insert({ID, this});
}
};
当我进行其他变量的静态初始化时,Test
的构造函数被Subclass
调用。是否存在在映射初始化之前调用Test
构造函数的情况?
mymap = {};
。如果不这样做,就会出现链接器错误。另一个问题:如何在不执行构造函数代码的情况下构造对象,它怎么可能是无关的? - barsdeveloper