访问static std :: map

时间:2016-01-15 12:53:26

标签: c++11 dictionary static

我试图重构一段相当复杂的代码并在加载库时遇到段错误。这是我可以挑出来作为segfault源的最小例子:

#include <iostream>
#include <string>
#include <map>

class Manager {
public:
  class Action{
  };
  static bool registerAction(const Action* a, const char* name);
};

namespace Actions {
  class ExampleAction : public Manager::Action {
  };
  namespace {
    static bool available = Manager::registerAction(new ExampleAction(),"ExampleAction");
  }
}

namespace {
  typedef std::map<const std::string,const Manager::Action*> ActionList;
  static ActionList sActions;
}

bool Manager::registerAction(const Action* a, const char* name){
  std::cout << "attempting to register action " << a << " as " << name << std::endl;
  sActions[name] = a;
  std::cout << "done" << std::endl;
  return true;
}

int main(){
  std::cout << "hello!" << std::endl;
  for(auto it:sActions){
    std::cout << it.first << std::endl;
  }
  std::cout << "world!" << std::endl;
  return 0;
}

使用--std=c++11标志用g ++ 4.8.4编译好,但执行时会发生这种情况:

attempting to register action 0x1ebe010 as ExampleAction
Segmentation fault (core dumped)

attempting to register首先出现,这当然是预料之中的,但是将值赋给静态地图实例的行会导致崩溃,我不明白原因。我可能在这里很愚蠢,但仍然 - 有关如何解决这个问题的任何建议吗?

0 个答案:

没有答案