2014-11-25 142 views
1

我有以下一段代码。我已经提取出来,我的课看起来是这样的:在std :: map中存储指向派生类实例的指针

#include<iostream> 
#include<map> 

using namespace std; 

template <class K> 
class Base { 
    private: 
     static std::map<std::string, Base*> derived_map; 
     //other private data 
    public: 
     Base(std::string modName) { 
      if (derived_map.find(modName) == derived_map.end()) 
      { 
       derived_map.insert(make_pair(modName, this)); 
      } 
     } 

}; 

template <class K> std::map<std::string, Base<K>*> Base<K>::derived_map; 

class Derived: public Base<Derived> 
{ 
    public: 
    Derived(std::string modname): Base<Derived>(modname) 
    { 
    } 
}; 


Derived obj("derived1"); // <<< This casuses segfault 
int main() 
{ 
} 

当我宣布派生的obj全球范围内,它出现segfaults。当我在主内部声明Derived obj时,它不会。我无法弄清楚我可能会做错什么。我想在我的基类中使用std :: map维护一个派生类指针列表。任何线索?

+0

http://stackoverflow.com/questions/1819131/c-static-member-initalization-template-fun-inside – 2014-11-25 06:08:43

+0

的可能的复制[OT ]:无需检查元素是否已经存在,然后尝试将其插入到'map'中,'map'已经这样做了。 – Jarod42 2014-11-25 08:24:44

回答

1

你有2个具有依赖性的全局变量:

obj要求Base<Derived>::derived_map正确初始化。

跨翻译单元的全局初始化以未定义的顺序完成。

你可能喜欢的东西解决你的代码:

template <class K> 
class Base { 
    private: 
     static std::map<std::string, Base*>& get_derived_map() 
     { 
      static std::map<std::string, Base*> derived_map; // initialized the first time 
                   // get_derived_map is called 
      return derived_map; 
     } 
     //other private data 
    public: 
     explicit Base(const std::string& modName) { 
      get_derived_map().insert(make_pair(modName, this)); 
     } 
}; 
相关问题