[] std::map 中的运算符给了我分段错误

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

本文关键字:运算符 分段 错误 std map      更新时间:2023-10-16

我有一个

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

然后我像下面这样插入:

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

这有时会引发分段错误。

为什么??

也许您的 myMap 无法再访问。例如,它可能是对已删除指针的引用,或者更有可能是对已删除类的成员变量的引用:

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();
}