views:

41

answers:

2

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.

+3  A: 

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.

James McNellis
+2  A: 

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.

Greg Hewgill
Thanks Greg. The reason, why I didn't want to use the way you suggested, was using non-def constructor, new MyClass(val). I was just confused with the deletion doubt.
Anton K