使用[]运算符首次访问map时出现段错误

时间:2011-12-11 01:38:42

标签: c++ map segmentation-fault

我在将字符串添加到将字符串链接到自定义类Node的映射时遇到了问题 我没有看到为什么问题可能是由静态初始化顺序引起的,而是将地图包装在一个函数中进行测试,并得到与以前相同的结果。我在三个文件中有以下代码:

在node.h中:

class Node
{
    public:
        const std::string name;
        Node (){};
        Node (std::string name, double x, double y);
        Node (const Node& b);
};

std::map<std:: string, Node>& nodeMap();

在node.cpp中:

map<string,Node>& nodeMap()
{
    static map<string,Node>* temp = new map<string, Node>();
    return *temp;
}
Node::Node (std::string name, double x, double y):name(name)
{
    nodeMap()[name]=*this;
}

在main.cpp中我初始化为:

itoa(i,i_str,10);
Node nI (i_str,rand(),rand());

程序编译正常,但运行时它会在nodeMap()[name]=*this上崩溃,调试器会返回

  

编程接收信号SIGSEGV,分段故障。   在ntdll!LdrWx86FormatVirtualImage()(C:\ Windows \ system32 \ ntdll.dll)

我确信我可能遗漏了一些明显的东西 - 我对c ++比较陌生 - 但无法弄清楚我的错误在哪里。

1 个答案:

答案 0 :(得分:0)

我不确定。但是在构造函数返回之前,您已经使用过Node的实例。

Node::Node (std::string name, double x, double y):name(name) // This is the constructor!
{ 
    nodeMap()[name]=*this; // You have tried to assign the current instance to map entry. NB: instance of Node is not finalized.
}

你应该编写像

这样的构造函数
Node::Node (std::string name, double x, double y):name(name) // This is the constructor!
{ 
}

然后在你的主要

Node nI(i_str, rand(), rand());
nodeMap()[nI.name]=nI;