I have the following piece of code. I have abstracted out and my class looks something like this:
#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()
{
}
When I declare the Derived obj globally, it segfaults. When I declared the Derived obj inside of my main then it doesn't. I am not able to figure out what I might be doing wrong. I am trying to maintain a list of derived class pointers in my base class using a std::map. Any clues ?