![](/img/trans.png)
[英]Can an unordered_map inside struct in c++ cause memory leak issues?
[英]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 y
從GUI::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.