删除std :: map中的新内存?

时间:2016-08-05 12:56:43

标签: c++ dictionary

假设我有一个指针地图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;

2 个答案:

答案 0 :(得分:5)

std::map包含键值对。因此当你做

for (auto& f : foos) {
    delete f;
}

f是一对,而不是您存储在地图中的指针。由于您没有分配它,因此无法在该对上调用delete。如果你想删除地图中的所有指针,那么你可以使用

for (auto& f : foos) {
    delete f.second;
}
foos.clear();

这将删除地图中的每个指针,然后clear()调用将清空地图,因此您没有一个已删除指针的地图。

我确实建议您使用普通值,如果可以,如果没有,那么至少使用智能指针。他们会为你处理内存释放。

答案 1 :(得分:2)

地图元素是键和值的std::pair,因此在这种情况下,您应该删除其second字段:

std::map<std::string, Foo*> foos;
foos.insert("blah", new Foo());

for (auto& f : foos) {
    delete f.second;
}