删除指针数组与删除指针向量 [英] Deleting an array of pointers vs deleting a vector of pointers
问题描述
当我们打电话
delete[] array; // array is a pointer to an array
或
delete[] vector; // vector is a pointer to a vector
假定它们是链接列表头指针的数组/向量:这2条语句是否为它们中的每个项目调用析构函数?还是我们应该遍历它们,删除每个项目,然后delete []数组或向量本身?
Assuming these are array/vector of linked list head pointers: Do these 2 statements call the destructors for every item in them? Or should we loop through them, delete each item and then delete[] the array or vector itself?
让我更具体一点, 如果该数组包含一个带有其析构函数的头指针,则它将删除其下一个节点或它指向的节点.
Let me be more specific, If the array holds a head pointer with its destructor is called it deletes its next node or that it points to.
推荐答案
您的第二个代码段不正确. delete
和delete[]
是两个不同的运算符. delete
用于删除由new
创建的实例,而delete[]
用于删除由new[]
创建的元素数组.
Your second code snippet is incorrect. delete
and delete[]
are two different operators. delete
is for delete an instance created by new
and delete[]
is for delete an array of elements created by new[]
.
在C ++中,数组和向量不关心它们存储的内容.对于数组和向量,都需要先删除每个项目(如果它们是使用new
分配的),然后再删除数组和向量.
In C++, arrays and vectors does not care about what they store. For both array and vector, you need to delete each item (if they were allocated using new
) before deleting the array and the vector.
如果您这样创建数组
Sample* arr[100];
for (int i = 0; i < 100; ++i) {
arr[i] = new Sample();
}
您需要像这样删除它们
for (int i = 0; i < 100; ++i) {
delete arr[i];
}
如果您创建这样的向量
vector<Sample*> arr;
for (int i = 0; i < 100; ++i) {
arr.push_back(new Sample());
}
您需要像这样删除
for (int i = 0; i < 100; ++i) {
delete arr[i];
}
这篇关于删除指针数组与删除指针向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!