Is there some difference in the following deletions of object array?
The first way:
MyClass **obj = new MyClass*[NUM];
for (int i=0; i<NUM; i++) obj[i] = new MyClass(val);
obj[0]->method();
for (int i=0; i<NUM; i++) delete obj[i]; /// Deletion1
delete obj; /// Deletion1
The second way:
MyClass **obj = new MyClass*[NUM];
for (int i=0; i<NUM; i++) obj[i] = new MyClass(val);
obj[0]->method();
delete[] obj; /// Deletion2
obj = 0x0; /// Deletion2
Both ways are workable and look similar in debugger.
In your first example, you are explicitly calling the destructor for each object pointed to by members of the allocated array. Then you are deleting the array of pointers (which should really be
delete[]because you allocated it as an array, but in practice for this example it probably doesn’t matter).In your second example, you are only deleting the array of pointers, which does not call the destructor for the pointed-to objects. The reason it doesn’t is that you may have made copies of those pointers in other variables which the compiler doesn’t necessarily know about.
If you were to create an array of objects and not pointers, like this:
then the
delete[]operator would automatically call the destructor for each of theNUMobjects in the allocated array.