【发布时间】:2013-05-03 17:12:37
【问题描述】:
我有一个 std::list 和一个 std::map 我想清空并在所有指针上调用 delete。
阅读this 问题后,我将其用于std::list:
mylist.remove_if([](myThingy* thingy) -> bool { delete thingy; return true; });
std::map 有类似简洁的东西吗?
请注意,我不能使用基于范围的 for 循环,因为我的编译器 (VC10) 不支持它。如果可能的话,我假设
for(auto* thingy : myMap) { delete thingy; }
myMap.clear();
会起作用的。如果我错了,请纠正我。
【问题讨论】:
-
你真的不应该将
std::list或std::map用于普通指针的集合。您应该使用旨在保存指针的集合或使用智能指针。如果您执行其中任何一项,您只需清空集合即可执行您想要的操作。 -
这是别人的旧代码,但是,哪些集合被设计为使用指针?
-
我支持 Sarien 的问题:“哪些集合设计为使用指针?”
-
boost::ptr_container boost.org/doc/libs/1_53_0/libs/ptr_container/doc/reference.html
-
@DavidSchwartz
std::map原始指针在导航中无处不在。 (当然,这里很明显map应该管理指针,而`std::shared_ptr 可能是个好主意。)