Consider the following situation:
Class** array = new Class*[8];
array[1] = new Class(1,2);
Is just doing “delete[ ] array” sufficient or should I precede the former with “delete array[1]“. I am not completely comfortable with memory management.
Every time you call
new[], you have to calldelete[]on the pointer to deallocate. Every time you callnew, you have to calldelete.In your case, you call
newtwice.array[1]contains a pointer to a class allocated withnew, so it must be deallocated withdelete. Andarrayis a pointer to an array allocated withnew[], so it must be freed withdelete[].Of course, you could have saved yourself this headache by simple declaring the array like this:
no dynamic memory allocation means no need to call
delete.Or using
std::vector: