在不超出范围的情况下解除分配 std::list

Deallocating std::list without going out of scope

在 STL 中,创建动态分配数组的方法之一是创建列表。当列表超出范围时,将调用每个元素的析构函数并删除列表。有没有办法在列表超出范围之前销毁列表(更重要的是释放使用的内存),如果可能的话,最好的方法是什么? delete[] 或 list::clear() 会完成这项工作吗?

In STL one of the ways to create a dynamically allocated array is to create a list.

链表和数组是完全不同的数据结构。

Is there a way to destroy list (and more importantly release the memory used) before list going out of scope

您可以使用 clear 成员函数删除 std::list 或任何其他标准容器(不包括 std::array)的所有元素。除了 std::vectorstd::basic_string 之外的所有标准容器在实际擦除元素时释放分配给元素的内存。您可以在清除后使用 shrink_to_fit 对向量和字符串实现相同的效果。

或者,缩小列表的范围可能是个好主意。

Will delete[] ... do the job?

没有。 delete[] 只能与指向使用分配 new-expression 创建的数组的第一个元素的指针一起使用。 std::list 不是使用分配 new-expression 创建的指针。您不能在 std::list.

上使用 delete[]