Deleting an array of pointers vs deleting a vector

2019-07-23 03:19发布

问题:

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.

回答1:

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];
}


回答2:

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();


回答3:

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.