[] operator in std::map is giving me segmentation

2019-09-22 00:25发布

I have a

std::map<std::string, myClass*> myMap

then I am inserting like follow:

if(!myKey.empty())
{
    myMap[myKey] = this;
}

This sometime is throwing a segmentation fault.

Why??

标签: c++ stdmap
1条回答
叼着烟拽天下
2楼-- · 2019-09-22 01:06

Maybe your myMap is no longer accessible. For instance, it might be a reference to a deleted pointer, or, much more probable, a member variable of an already deleted class:

class MyClass {
  public:
    selfInsert(std::string myKey) {
      if(!myKey.empty()) {
        myMap[myKey] = this;
      }
    }

  private:
    std::map<std::string, myClass*> myMap;
}

int main()
{
  MyClass *a = new MyClass();
  delete a;
  a->selfInsert();
}
查看更多
登录 后发表回答