以下代码块似乎运行良好 生成:
添加 1000 件事 _MyMap 现在拥有 [1000] 个东西 _MyMap 被释放并被删除。现在尺寸 [0]
#include <unordered_map>
#include <iostream>
typedef struct _entry
{
int now;
} ENTRY, * PENTRY;
std::unordered_map<int, PENTRY> _MyMap;
typedef std::unordered_map<int, PENTRY>::iterator itEntry;
int Now()
{
return 10;
}
主要功能,添加注释,因为该网站不允许我只添加代码
int main()
{
PENTRY pE = NULL;
std::pair<itEntry, bool> r;
printf("Add 1000 things\n");
for (int i = 0; i < 1000; i++)
{
pE = (PENTRY)malloc(sizeof(ENTRY));
pE->now = Now();
r = _MyMap.insert(std::make_pair(i, pE));
if (false == r.second)
{
printf("For some crazy reason its already there\n");
continue;
}
}
// OK, theres probably 1000 things in there now
printf("_MyMap now holds [%u] things\n", _MyMap.size() );
// The following seems stupid, but I don't understand how to free the memory otherwise
for (int i = 0; i < 1000; i++)
{
// first query
auto it = _MyMap.find(i);
// if malloc failed on an attempt earlier this could be NULL right?
// I've had free impls crash when given NULL, so I check.
if (it != _MyMap.end() &&
NULL != it->second)
free(it->second);
// second query
_MyMap.erase(i);
}
printf("_MyMap free'd and erased. size now [%u]\n", _MyMap.size());
return 0;
}
问题内嵌在评论中
最佳答案
您可能想要这个:
auto it = _Map.find(idUser);
if (it != _Map.end())
{
free(it->second);
_Map.erase (it);
}
但是以这种方式将原始指针存储在集合中确实不是一个好主意。理想情况下,您应该将数据直接存储在映射中,而不是存储指向它的指针。否则,使用 std::unique_ptr 以便指针的销毁自动释放数据。
关于c++ - std::unordered_map 如何释放使用 malloc 创建的结构。是否需要对 map 进行 2 次查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55716512/