完全删除 std::map<int、string> 的内存
Delete memory of std::map<int, string> completely
我有一个地图填充,现在我想完全删除内存。我该怎么做呢?无法找到任何特定的这个主题,抱歉,如果它已经回答…
我的代码是这样的: for(std::map<short,std::string>::iterator ii=map.begin();
ii!=map.end(); ++ii)
{
delete ⅈ
}
但是它不起作用。有人能帮忙吗?
问候,菲尔。
正确的方法是不去做。当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();
}
相关文章:
- 在共享缓冲区内存中创建 ::std::string 对象
- 内存未释放 std::list<std::shared_ptr<std::string>> C++
- 在先前调用 string::find 后添加内存分配和内存集会导致它返回 npos.为什么?
- 让 'std::vector<unsigned char>' 从 'std::string' 中窃取内存
- 如何在<N>不发生内存泄漏的情况下同时(线程安全)填充 c++11 std::map<std::string,std::bitset*>?
- 使用 boost::interprocess 共享内存时从 std::string 转换为 "MyShmString"
- std :: string ::擦除会导致内存损坏
- MISRA C++(规则 18-4-1)和动态内存分配 - 是否允许 std::string
- 通过读取文件创建映射<字符串,矢量>时如何管理内存<string>
- 使用std :: String键在共享内存中升级无序地图
- 返回 std::string 时出现瓦尔格林德内存泄漏
- 如果函数返回 std::vector<std::string>,是否存在内存泄漏?
- std::string试图释放错误的内存
- 执行std::string::clear回收与字符串关联的内存
- std::string是否对分配的内存进行重新计数?如何通过值传递和通过引用传递不同的std::string大小写
- String.replace() 和动态内存
- 'std::string::c_str()'如何返回不会导致内存泄漏或未定义的 C 字符串内容的 C 字符串?
- 如果我在 C++ 中为 "std::string &" 类型的参数指定默认值,这会导致内存泄漏吗?
- 为什么libc++的std::string实现占用了libstdc++的3倍内存?
- 使用 c_str() 返回的指针删除动态分配的 std::string 是否会导致C++内存泄漏