Reputation: 4798
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.
Upvotes: 2
Views: 88
Reputation: 993163
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:
MyClass *obj = new MyClass[NUM];
then the delete[]
operator would automatically call the destructor for each of the NUM
objects in the allocated array.
Upvotes: 3
Reputation: 355069
Both are incorrect. The correct way would be:
for (int i = 0; i < NUM; i++) delete obj[i];
delete[] obj;
In the first way you show, you use delete
to destroy an object allocated with new[]
, which results in undefined behavior (if you use new[]
, you must destroy the object using delete[]
).
In the second way you show, you leak all of the pointers that you created in the first for loop.
If you use std::vector
instead of dynamically allocated arrays and some type of smart pointer, then you don't have to worry about this in most code.
Upvotes: 4