简体   繁体   English

删除std :: map的内存 <int, string> 全然

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

I have a map filled with and now I want to delete the memory completely. 我有一张地图,现在我想完全删除内存。 How do I do this right? 我该怎么做? couldn't find anything specific for this topic, sorry if it is already answered... 找不到任何针对这个主题的内容,对不起,如果已经回答了......

my code is something like this: 我的代码是这样的:

      for(std::map<short,std::string>::iterator ii=map.begin();   
ii!=map.end(); ++ii)
    {
        delete &ii;
    }

But it doesnt work. 但它不起作用。 Can anybody help pls? 有人可以帮忙吗?

regards, phil 问候,菲尔

The way to do it right is not to do it. 做正确的方法不是这样做。 A map will automatically release resources when it's destroyed for anything allocated automatically. 对于自动分配的任何内容, map将自动释放资源。

Unless you allocated the values with new , you don't delete them. 除非您使用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];
}

Simply call map.clear(); 只需调用map.clear(); . This will release all objects the map has allocated internally. 这将释放地图在内部分配的所有对象。

Note that in system tools like the task manager, your application can still show the same amount of memory occupied. 请注意,在任务管理器等系统工具中,您的应用程序仍然可以显示相同的内存量。 It's perfectly possible the OS decides not to reclaim the memory your process once held, in case it allocated it again. 操作系统决定不再回收您的进程曾经保存的内存,以防再次分配它。 It would reclaim it later if it started to run short. 如果它开始不足,它会在以后收回它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM