[英]C++/STL - Program crashes when accessing class pointer instance in a std::map
好的,我有一个函数,它读取xml文件并使用new创建控件并将它们存储在名为Window
的类的公共成员变量中:
std::map<const char*, Button*> Buttons;
std::map<const char*, TextBox*> TextBoxes;
std::map<const char*, CheckBox*> CheckBoxes;
Button,TextBox和CheckBox类是CreateWindowEx的自制包装器。
这是填充地图的函数:
void Window::LoadFromXml(const char* fileName)
{
XMLNode root = XMLNode::openFileHelper(fileName, "Window");
for(int i = 0; i < root.nChildNode("Button"); i++)
{
Buttons.insert(std::pair<const char*, Button*>(root.getChildNode("Button", i).getAttribute("Name"), new Button));
Buttons[root.getChildNode("Button", i).getAttribute("Name")]->Init(_handle);
}
for(int i = 0; i < root.nChildNode("CheckBox"); i++)
{
CheckBoxes.insert(std::pair<const char*, CheckBox*>(root.getChildNode("Button", i).getAttribute("CheckBox"), new CheckBox));
CheckBoxes[root.getChildNode("CheckBox", i).getAttribute("Name")]->Init(_handle);
}
for(int i = 0; i < root.nChildNode("TextBox"); i++)
{
TextBoxes.insert(std::pair<const char*, TextBox*>(root.getChildNode("TextBox", i).getAttribute("Name"), new TextBox));
TextBoxes[root.getChildNode("TextBox", i).getAttribute("Name")]->Init(_handle);
}
}
这是xml文件:
<Window>
<TextBox Name="Email" />
<TextBox Name="Password" />
<CheckBox Name="SaveEmail" />
<CheckBox Name="SavePassword" />
<Button Name="Login" />
</Window>
问题是,如果我尝试访问,例如, TextBoxes["Email"]->Width(10);
,程序编译得很好,但是当我启动它时会崩溃。
我是从派生类调用它:
class LoginWindow : public Window
{
public:
bool OnInit(void) // This function is called by Window after CreateWindowEx and a hwnd == NULL check
{
this->LoadFromXml("xml\\LoginWindow.xml"); // the file path is right
this->TextBoxes["Email"]->Width(10); // Crash, if I remove this it works and all the controls are there
}
}
问题可能是,你的地图有const char*
作为键 - 这并不意味着字符串,而是指针。 这意味着它看到两个不同的指向同一个字符串的指针(例如你的字符串文字“电子邮件”和你从文件中读取的字符“电子邮件”)不同,因此它找不到指向文本框的指针崩溃“行(并执行不存在的对象的方法)。 我建议你将你的地图类型改为std::map<std::string, ...>
。
除此之外,我建议你使用std::make_pair(a, b)
而不是手动指定对结构的类型。
什么像root.getChildNode("Button", i).getAttribute("CheckBox")
返回? 很明显它是一个char*
(也许是const),但它在哪里分配? 堆? 如果是这样,你何时释放它?
根据API,它可能会返回静态缓冲区或其他不会持续时间的map
,这可能会导致崩溃和其他时髦的行为。 你应该让你的map
看起来像这样,而不必担心它:
std::map<std::string, Button*> Buttons;
std::map<std::string, TextBox*> TextBoxes;
std::map<std::string, CheckBox*> CheckBoxes;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.