Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete[] an array of objects

I have allocated and array of Objects

Objects *array = new Objects[N]; 

How should I delete this array? Just

delete[] array; 

or with iterating over the array's elements?

for(int i=0;i<N;i++)     delete array[i]; delete[]; 

Thanks

UPDATE:

I changed loop body as

delete &array[i]; 

to force the code to compile.

like image 984
osgx Avatar asked Mar 21 '10 05:03

osgx


People also ask

What does delete [] array do in C++?

operator delete[] Default deallocation functions (array form). Deallocates the memory block pointed to by ptr (if not null), releasing the storage space previously allocated to it by a call to operator new[] and rendering that pointer location invalid.

How do you delete an array of objects in C++?

In C++, the single object of the class which is created at runtime using a new operator is deleted by using the delete operator, while the array of objects is deleted using the delete[] operator so that it cannot lead to a memory leak.


2 Answers

Every use of new should be balanced by a delete, and every use of new[] should be balanced by delete[].

for(int i=0;i<N;i++)     delete array[i]; delete[] array; 

That would be appropriate only if you initialized the array as:

Objects **array = new Objects*[N]; for (int i = 0; i < N; i++) {      array[i] = new Object; } 

The fact that your original code gave you a compilation error is a strong hint that you're doing something wrong.

BTW, obligatory: avoid allocating arrays with new[]; use std::vector instead, and then its destructor will take care of cleanup for you. Additionally it will be exception-safe by not leaking memory if exceptions are thrown.

like image 159
jamesdlin Avatar answered Oct 16 '22 14:10

jamesdlin


Just delete[] array is sufficient. It is guaranteed that each element of the array is deleted when you delete an array using delete[] operator.

like image 26
Naveen Avatar answered Oct 16 '22 14:10

Naveen