![](/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.