簡體   English   中英

C ++ / STL - 在訪問std :: map中的類指針實例時程序崩潰

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM