简体   繁体   English

删除std :: list的内容

[英]Deleting content of a std::list

I have a list of pointers which I don't need anymore. 我有一个不再需要的指针列表。 To delete all of them, I can normally iterate the list: 要删除所有这些,我通常可以迭代该列表:

for (T* ptr: mylist) {
    delete ptr;
}

Or I can delete the first or last element until the list is empty: 或者,我可以删除第一个或最后一个元素,直到列表为空:

while (!mylist.empty()) {
    delete mylist.front(); //or mylist.back()
    mylist.pop_front(); //or mylist.pop_back()
}

What is the preferred way, both for performance and clarity? 为了提高性能和清晰度,首选的方法是什么?

The best way is to store std::unique_ptr's in list and not manage memory yourself. 最好的方法是将std::unique_ptr's存储在列表中,而不自己管理内存。 Then you just do mylist.clear() . 然后,您只需执行mylist.clear()

They do two different things. 他们做两件事。 The second leaves you with an empty list. 第二个留给您一个空列表。 The first leaves you with a list that holds a bunch of invalid pointers; 第一个为您提供了一个列表,其中包含一堆无效的指针; that may or may not matter, depending on what happens to the list after this operation. 这可能会或可能不会很重要,具体取决于此操作后列表发生的情况。

I would use your first example. 我会用你的第一个例子。 For best practice you should clear your list afterwards to ensure no invalid pointers are left in it. 为了获得最佳实践,您应该在之后清除列表,以确保其中没有任何无效的指针。

for (T* ptr : mylist) delete ptr;
mylist.clear();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM