Would the following properly destroy everything (all appropriate destructors called and all memory freed)?
Class* var[50];
var[0] = new SubClass();
delete[] *var;
Similar to
Class** var = new Class*[50];
var[0] = new SubClass();
delete[] var;
Or should I be iterating over the array and delete each individual object (which is what I thought delete[] did).
This is undefined behavior. The proper way is
If you allocate memory for all 50 elements of the array, then you have to iterate and delete each one of them. Think of it this way:
new, you should have an associateddeletenew[], you should have an associatedelete[]newwithdelete[]andnew[]withdeleteas it leads to undefined behaviorYour second snippet is illegal C++.
EDIT As you’re clearly a beginner, let’s break this down a bit. Since the second snippet doesn’t even compile, I’m going to focus on the first one:
This declares an array of 50 pointers to
Class. The pointers are dangling – they are not initialized andClassobjects aren’t created.This allocates memory for a
SubClassobject and assigns the first pointer in the array. All other pointers remain uninitialized.returns the first element, which is a
Class*. It’s equivalent tovar[0].attempts to call
delete[]on aClass*, which was allocated withnew, so it results in undefined behavior.