Deleting an array of pointers vs deleting a vector

2019-07-23 03:51发布

When we call

delete[] array; // array is a pointer to an array

or

delete[] vector; // vector is a pointer to a vector

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.

3条回答
Rolldiameter
2楼-- · 2019-07-23 03:59

Calling delete[] on a std::vector is not correct C++. The vector is destroyed when it goes out of scope or when you delete a pointer to it if allocated on the heap with new. In both cases, however, destroying the array/vector does not call delete on the pointers it contains - you need to iterate through and do this yourself if you need to free that memory.

查看更多
甜甜的少女心
3楼-- · 2019-07-23 04:09

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[].

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.

If you create the array like this

Sample* arr[100];
for (int i = 0; i < 100; ++i) {
    arr[i] = new Sample();
}

you need to delete them like this

for (int i = 0; i < 100; ++i) {
    delete arr[i];
}

If you create the vector like this

vector<Sample*> arr;
for (int i = 0; i < 100; ++i) {
    arr.push_back(new Sample());
}

you need to delete like this

for (int i = 0; i < 100; ++i) {
    delete arr[i];
}
查看更多
该账号已被封号
4楼-- · 2019-07-23 04:25

Deleting an array of pointers delete[] array is suitable, but for an vector of pointers i would use a construct like this:

std::vector<Data*> m_data;
while(!m_data.empty()) delete m_data.back(), m_data.pop_back();
查看更多
登录 后发表回答