C++ 删除新的';std::map中的d内存?
假设我有一个新的指针映射,我如何遍历这个映射并干净地删除它们?以下是我尝试过的:C++ 删除新的';std::map中的d内存?,c++,dictionary,C++,Dictionary,假设我有一个新的指针映射,我如何遍历这个映射并干净地删除它们?以下是我尝试过的: std::map<std::string, Foo*> foos; foos.insert(std::make_pair("blah", new Foo())); for (auto& f : foos) { delete f; } std::map foos; insert(std::make_pair(“blah”,new Foo()); 用于(自动&f:foos){ 删除f;
std::map<std::string, Foo*> foos;
foos.insert(std::make_pair("blah", new Foo()));
for (auto& f : foos) {
delete f;
}
std::map foos;
insert(std::make_pair(“blah”,new Foo());
用于(自动&f:foos){
删除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;
$g++test.c-std=c++14
test.c:在函数“int main()”中:
test.c:12:12:错误:类型'struct std::pair'参数指定给'delete',应为指针
删除f;
映射元素是键和值的std::pair
,因此在这种情况下,您应该删除其第二个
字段:
std::map<std::string, Foo*> foos;
foos.insert("blah", new Foo());
for (auto& f : foos) {
delete f.second;
}
std::map foos;
插入(“废话”,新的Foo());
用于(自动&f:foos){
删除f.second;
}
Astd::map
包含键值对。所以当你这样做的时候
for (auto& f : foos) {
delete f;
}
f
是一对,而不是存储在地图中的指针。您不能对该对调用delete
,因为您没有分配它。如果要删除映射中的所有指针,则可以使用
for (auto& f : foos) {
delete f.second;
}
foos.clear();
这将删除映射中的每个指针,然后调用clear()
将清空映射,这样您就不会有一个满是已删除指针的映射
我建议,如果可以的话,使用普通值,如果不可以的话,至少使用智能指针。他们将为您处理内存释放。使用智能指针并让他们处理。好吧,但如果我不想使用智能指针怎么办?@Jee,那就不要使用它们。@Jee如果
blah
已经作为密钥存在,那么您的代码将创建泄漏。因为insert
不会将数据插入地图。@Jee如果密钥已经存在,insert
不会将数据插入地图。这会给您留下一个无法恢复的分配对象,从而导致泄漏。请阅读