std::unordered_map 如何释放使用 malloc 创建的结构。是否需要对地图进行 2 次查询?

std::unordered_map how to free struct created with malloc. Are 2 queries into the map required?

下面的代码块似乎 运行 没问题 生成:

添加 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,使指针销毁自动释放数据。