std :: unordered_map如何释放用malloc创建的struct。是否需要2个查询到地图?

问题描述 投票:1回答:1

以下代码块似乎运行良好Generate:

添加1000个东西_MyMap现在拥有[1000]的东西_MyMap free'd and erased。现在大小[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;
}

问题在评论中是内联的

c++ malloc unordered-map
1个回答
3
投票

你可能想要这个:

auto it = _Map.find(idUser);    
if (it != _Map.end())
{
    free(it->second);
    _Map.erase (it);
}

但是以这种方式将原始指针存储在集合中真的不是一个好主意。理想情况下,您应该直接将数据存储在地图中,而不是存储指向它的指针。否则,使用std::unique_ptr以便指针的销毁自动释放数据。

© www.soinside.com 2019 - 2024. All rights reserved.