簡體   English   中英

C ++ - struct的unordered_map內存問題

[英]C++ - unordered_map memory issues with struct

我決定今天將我的代碼從vector更改為unordered_map這樣我就可以擁有字符串鍵值。 但是,似乎unordered_map並沒有完全解決。

所以基本上我有一個結構類型:

typedef struct WindowData //the infamous Window Data struct
{
    HWND handle;
    std::unordered_map<std::string, WindowData*> children;
    COLORREF color;
    int height;
    int width;
    int x;
    int y;
    WindowData *parent;
    bool visible;
} windowData;

然后是全局定義的實例:

WindowData MainWData = {NULL, std::unordered_map<std::string, WindowData*>(), NULL, 0, 0, 0, 0, NULL, true};

然后一個函數將一個元素添加到unordered_list (struct member children ):

void GUI::CreateTitle(WindowData *data) //Home/About page title
{
    /*...*/
    WindowData wd={handle, std::unordered_map<std::string, WindowData*>(), ColorPalette.BackgroundColor, Nheight, Nwidth, x, y, data, true}; //all these values are defined within the scope of this function except ColorPalette, which is global
    data->children.insert(std::make_pair("title", &wd));
}

最后,我有幾個其他函數,包括GUI類的成員和非成員,它們讀取map元素,例如:

void GUI::CreateAboutButton(WindowData *data) //Home Page About Button
{
    /*...*/
    int y=data->children.at("title")->y + data->children.at("title")->height + 100;
    /*...*/
}

現在,來描述錯誤。 int yGUI::CreateAboutButton()函數。 每次運行程序時,該值應該相同。 通常,它類似於219.但是,現在,它每次運行程序時都會更改。 有時y是正確的值。 其他時間是0.其他時候它大於40 000。

我知道這是一個內存問題,因為有時當程序運行時,它會立即發出段錯誤信號,當它沒有時,Memory博士會顯示二十多個“未初始化讀取”錯誤。 我的猜測是因為unordered_map值必須是指向struct的指針(如果只是struct值而不是指針,程序就不會編譯),只要GUI::CreateTitle()的struct實例wd熄滅范圍,地圖仍然指向其舊的內存位置而不是實際的實例。 但我不知道怎么做(這是我第一次實現unordered_map )是解決問題。 我嘗試為unordered_map::emplace切換unordered_map::insert ,但這導致了一個段錯誤。

任何幫助表示贊賞。

編輯:下面評論中的診斷/解決方案讓我通過將wd定義為該類的公共成員來解決問題。 它現在工作正常,並解決了所有內存錯誤。

問題是在地圖中存儲指向局部變量wd的指針。 CreateTitle結束時銷毀局部變量,並且地圖中的指針變為懸空。 一種可能的解決方案是讓地圖擁有子WindowData ,例如使用unique_ptr

std::unordered_map<std::string, std::unique_ptr<WindowData>> children;

然后在適當的位置創建它:

void GUI::CreateTitle(WindowData *data)
{
    /*...*/
    data->children.emplace(
        "title",
        make_unique<WindowData>(handle, std::unordered_map<std::string, std::unique_ptr<WindowData>>(), ColorPalette.BackgroundColor, Nheight, Nwidth, x, y, data, true)
    );
}

添加編輯:將wd定義為WindowData的公共成員僅在只有一個子WindowData時才有效。 然而,擁有地圖是沒有意義的,不是嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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