samedi 3 octobre 2020

segment fault when inserting element into a gloable std::map in c++

This problem blocks me moving ahead. Please anyone kindly help me out.

My purpose is to implement a plugin factory which can create a plugin object by it's name(something like reflection, I guess?),

I define a namespace in header like:

// header file
namespace PluginFactory
{
  using MFP = std::function<IPlugin*()>;
  typedef std::map<std::string, MFP > mapType;

  extern mapType  g_ConstructMap;
  //extern std::map<std::string, int> mMap;

  extern IPlugin *CreateInstance(const std::string &className);

  template<typename T>
  IPlugin * createPlugin()
  {
    return new T;
  }

  template <typename T>
  extern void InsertMap(const std::string &pluginName)
  {
    g_ConstructMap.insert(std::make_pair(pluginName, &createPlugin<T>));
    //mMap.insert(std::make_pair(pluginName, 0));
  }
}
// source file
namespace  PluginFactory
{

  mapType  g_ConstructMap;
  std::map<std::string, int> mMap;

  IPlugin * CreateInstance(const std::string &className)
  {
    mapType::iterator it = g_ConstructMap.find(className);
    if(it == g_ConstructMap.end())
    {
      qWarning("Construct %s failed. Not find a construct in map.", className.c_str());
      return nullptr;
    }
    return it->second();
  }
}

and the register

template<typename T>
class PluginFactoryRegister
{
public:
  PluginFactoryRegister(const std::string &pluginName)
  {
    PluginFactory::InsertMap<T>(pluginName);
  }
};

Register a specific plugin class into this system, using the macro:

#define REGISTER_DEF_TYPE(NAME) \
    PluginFactoryRegister<NAME> NAME::regTbl(#NAME)

#define ADD_REGISTER_TABLE(NAME) \
    static PluginFactoryRegister<NAME> regTbl

Finnaly, call insert function in PluginFactoryRegister.

But, every time I run application, it complains Segment fault in exactly line:

namespace PluginFactory
{
...
   g_ConstructMap.insert(std::make_pair(pluginName, &createPlugin<T>));
...
}

Surely, I have tried many solutions, like define as class static map. That can barely help me.

Aucun commentaire:

Enregistrer un commentaire