完全删除 std::map<int、string> 的内存

Delete memory of std::map<int, string> completely

本文关键字:内存 string int gt lt 删除 std map      更新时间:2023-10-16

我有一个地图填充,现在我想完全删除内存。我该怎么做呢?无法找到任何特定的这个主题,抱歉,如果它已经回答…

我的代码是这样的:
      for(std::map<short,std::string>::iterator ii=map.begin();   
ii!=map.end(); ++ii)
    {
        delete &ii;
    }

但是它不起作用。有人能帮忙吗?

问候,菲尔。

正确的方法是不去做。当map被自动分配的资源销毁时,它会自动释放资源。

除非您用new分配值,否则您不会将它们delete

{
    std::map<short,std::string> x;
    x[0] = "str";
}
//no leaks here
{
    std::map<short,std::string*> x;
    x[0] = new std::string;  
    delete x[0];
}

直接调用map.clear();。这将释放map内部分配的所有对象。

请注意,在任务管理器等系统工具中,应用程序仍然可以显示相同数量的内存占用。操作系统完全有可能决定不回收您的进程曾经占用的内存,以防它再次分配内存。

if(m_mapModels.size() > 0)
{
    for(map<short,std::string>::iterator it=m_mapModels.begin() ; it!=m_mapModels.end() ; it++)
    {
        delete it->second;
    }
    m_mapModels.clear();
}
相关文章: