【问题标题】:C++/STL - Program crashes when accessing class pointer instance in a std::mapC++/STL - 访问 std::map 中的类指针实例时程序崩溃
【发布时间】:2010-08-11 21:16:41
【问题描述】:

好的,我有一个函数可以读取 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"]-&gt;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
    }
}

【问题讨论】:

    标签: c++ xml pointers winapi stl


    【解决方案1】:

    问题可能是,您的地图有 const char* 作为键 - 这并不意味着字符串,而是指针。这意味着它看到两个指向相同字符串的不同指针(例如,您的字符串文字“Email”和您从文件中读取的字符“Email”)是不同的,因此它找不到指向文本框的指针“ crash" 行(并改为执行不存在对象的方法)。我建议您将地图类型更改为std::map&lt;std::string, ...&gt;

    除此之外,我建议您使用std::make_pair(a, b) 而不是手动指定对结构的类型。

    【讨论】:

    • 谢谢,jpalecek,顺便说一句,这是初学者、中级还是高级问题?
    【解决方案2】:

    root.getChildNode("Button", i).getAttribute("CheckBox") 之类的返回值是什么?显然它是一个char*(可能是常量),但它分配在哪里?堆?如果有,什么时候释放?

    根据 API 的不同,它可能会返回一个静态缓冲区或其他不会像您的 map 那样持续时间长的东西,这可能会导致崩溃和其他时髦的行为。你应该让你的maps 看起来像这样,而不必担心它:

    std::map<std::string, Button*> Buttons;
    std::map<std::string, TextBox*> TextBoxes;
    std::map<std::string, CheckBox*> CheckBoxes;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-22
      • 2010-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-11
      相关资源
      最近更新 更多