删除标准::映射中的新内存?
Deleting new'd memory in a std::map?
假设我有一个new
的指针映射,我如何迭代该映射并干净地删除它们?以下是我尝试过的:
std::map<std::string, Foo*> foos;
foos.insert(std::make_pair("blah", new Foo()));
for (auto& f : foos) {
delete f;
}
虽然它似乎不起作用,但我得到了以下错误。
$ g++ test.c -std=c++14
test.c: In function 'int main()':
test.c:12:12: error: type 'struct std::pair<const std::basic_string<char>, Foo*>' argument given to 'delete', expected pointer
delete f;
std::map
包含键值对。因此,当你进行时
for (auto& f : foos) {
delete f;
}
f
是一对,而不是存储在映射中的指针。你不能在该对上调用delete
,因为你没有分配它。如果你想删除映射中的所有指针,那么你可以使用
for (auto& f : foos) {
delete f.second;
}
foos.clear();
这将删除映射中的每个指针,然后clear()
调用将清空映射,这样就不会有一个充满已删除指针的映射。
不过,我确实建议您尽可能使用纯值,如果不能,那么至少使用智能指针。它们将为您处理内存释放。
map元素是键和值的std::pair
,因此在这种情况下,您应该删除其second
字段:
std::map<std::string, Foo*> foos;
foos.insert("blah", new Foo());
for (auto& f : foos) {
delete f.second;
}
相关文章:
- 了解内存序列和标准::memory_order_relaxed
- 目标c是否需要一个标准来定义像c++11这样的内存模型
- 在C++标准中记录对象的内存布局的哪个位置?
- 如何使用 RPM 从内存中读取标准::字符串
- 标准::矢量增加峰值内存
- 标准::shared_ptr(s) 和内存泄漏
- 标准::字符串中的内存泄漏
- 了解标准::原子内存屏障
- C++标准库中是否有保证不执行动态内存分配的函数或类
- 如果malloc/free对显然做了同样的工作,为什么C++标准库容器使用内存池
- 为什么C 标准专门为具有不同访问说明符的类数据成员的内存布局提供了余地
- 内存效率标准::地图替代
- C++对间接运算符的标准描述是否保证内存写入不会被优化掉
- win32 标准::线程泄漏内存
- 复制有状态分配器:标准库分配器语义和内部内存
- 可视标准::队列内存消耗导致内存泄漏 - C++
- 将内存复制到标准::复制
- 如何以标准方式从未对齐的内存中获取值
- 带有标准容器和常量引用的c++代码显示出意外的内存
- 标准::字符串使用的可用内存