I’m running into a problem adding an element to a map linking strings to a custom class Node.
I saw no reason why the problem could have been caused by static initialization order, but wrapped the map in a function to test, and got the same results as before. I have the following code in three files:
In 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();
In 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;
}
And in main.cpp I initialize with:
itoa(i,i_str,10);
Node nI (i_str,rand(),rand());
The program compiles fine, but when it runs it crashes on nodeMap()[name]=*this, and the debugger returns
Program received signal SIGSEGV, Segmentation fault.
In ntdll!LdrWx86FormatVirtualImage () (C:\Windows\system32\ntdll.dll)
I’m sure I’m probably missing something obvious – I’m relatively new to c++ – but can’t figure out where my error is.
I’m not sure about it. But you have used the instance of Node before its constructor returns.
You should write constructor like
then in your main