如何有效删除C++对象存储在多个容器中?自动指针?
我有一个应用程序,它在执行期间创建某种类型的对象(比方说,“Foo”类),以跟踪一些统计数据,并将它们插入两个 STL 映射中的一个或两个中,比如说:
map<Foo*, int> map1;
map<Foo*, int> map2;
我想知道什么是最好的删除 Foo 对象的方法。目前我的解决方案是迭代map1和map2,并将Foo指针放入一个集合中,然后对该集合进行交互并在每个集合上调用delete。
有没有更有效的方法,可能使用 auto_ptr ?如果是这样怎么办,因为 auto_ptr<>对象不能存储在STL容器中吗?
提前致谢。
I have an application which creates objects of a certain kind (let's say, of "Foo" class) during execution, to track some statistics, and insert them into one or both of two STL maps, say:
map<Foo*, int> map1;
map<Foo*, int> map2;
I was wondering what is the best way to delete the Foo objects. At the moment my solution is to iterate over map1 and map2, and put the Foo pointers into a set, then interating on this set and call delete on each.
Is there a more effective way, possibly using auto_ptr? If so how, since auto_ptr<> objects can't be stored in STL containers?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正如您所说,
auto_ptr
对象不能存储在 STL 容器中。我喜欢使用shared_ptr
对象(来自 boost)来达到此目的。它是一个引用计数指针,因此当对象超出范围时,只会删除一次。现在,您只需从
map1
和map2
中添加和删除shared_ptr
对象,因为它们是指针,并且它们将在以下情况下负责删除:最后一个引用被删除。auto_ptr
objects cannot, as you say, be stored in STL containers. I like to use theshared_ptr
object (from boost) for this purpose. It is a referenced counted pointer, so the object will be deleted once only, when it goes out of scope.Now, you just add and remove from
map1
andmap2
,shared_ptr
objects as they were pointers, and they will take care of the deletion, when the last reference is removed.使用 boost::shared_ptr - 它专门用于可以从多个位置引用对象的情况。使用 auto_ptr 在这里不是一个选项 - 一旦对象的第一个 auto_ptr 被销毁,第二个 auto_ptr 就会留下一个悬空指针,这是导致未定义行为的直接方式。
Use boost::shared_ptr - it's specifically intended for cases where the object can be referenced from multiple locations. Using auto_ptr is not an option here - once the first auto_ptr to an object is destroyde the second one is left with a dangling pointer and that's direct way to undefined behaviour.
我想您需要一个主列表或一组对象,如果您有能力复制它们,则可以通过值保存它们,或者更可能通过指针保存,以便您可以复制指针并将它们放入其他集合中。
这些其他集合(示例中的
map1
和map2
)可以随时插入和删除这些指针。当您最终想要删除所有内容时,您可能可以只删除映射,或者让它们超出范围,或者忽略它们,然后返回主列表并迭代删除找到的指针。I guess you need a master list or set of objects, either held by value if you can afford to copy them, or more likely held by pointer so you can copy the pointer and put them into other collections.
These other collections (
map1
andmap2
in your example) can have these pointers inserted and removed at any time. When finally you want to delete everything, you can probably just delete the maps, or let them go out of scope, or ignore them, and just once, go back to the master list and iterate through that deleting the pointers that are found.http://ootips.org/yonat/4dev/smart-pointers.html 讨论可以存储在 STL 容器中的某些类型的智能指针。 参见此处
http://ootips.org/yonat/4dev/smart-pointers.html talks about certain kinds of smart pointers that may be storeable in STL containers. See here