I have an array of pointers (that I created by calling new ptr*[size]). All of these pointers point to an object that was also put on the heap.
What is the proper way to delete the array and all new’d ptr’s?
This is what I do now:
for (int i = 0; i < size; i++) delete array[i];
delete[] array; // Not sure since this double deletes array[0]
Does this do what I think it should?
Thanks
Every pointer allocated with
newgets a correspondingdelete. Every pointer allocated withnew []gets a correspondingdelete []. That’s really all you need to know. Of course, when you have a dynamically allocated array which contains dynamically allocated pointers the deallocation must occur in reverse order.So it follows that the correct idiom would be…
And then of course I say “stop doing that” and recommend you use a
std::arrayorstd::vector(and the template type would beunique_ptr<int>).