• Register

In C++, we often need to delete something that can be any data or content {elements} of a variable. To delete something. Programmers use the delete() function and delete[] operator. Both of them seem to be similar, but there is a difference between them.

 

Delete

Delete is an operator which is used to delete non-array objects. Often those objects are created by new expressions. Here the new expression is used to allocate memory dynamically, and the new operator puts variables on the heap.

 

Delete[]

Delete[] operator is also a fixed function, and that can be provoked as any other function. But the delete[] operator has unique use or we can say behaviour. It is a deallocation function and as the name suggests it is used to deallocate arrays, i.e., freeing the memory space occupied by the array. The delete[] operator deallocates the array differently, according to it first we need to call all the destructors for each element in the array and then it calls the deallocation function to deallocate the array.

 

Explanation with illustration

Consider we have a class containing pointer like this

Class ABC{}

ABC *ptr = new ABC[100]

 

So in this case, if we use the delete[] operator. As in the code, new ABC[100] provides information to the compiler and lets the compiler know how many objects that need to be deallocate and will call a destructor for each. Here, the number of objects is 100.

But if we don’t use delete[] and we use delete ptr for this program, then the compiler will be unknown of the number of objects to be deallocate. So, it will end up calling only one destructor which will delete only one object and the remaining 99 objects are still occupying memory that should be deallocate.

So, it will cause a memory leak.

 

Conclusion

The major difference between delete and delete[] is that delete is used to deallocate memory occupied by a single object. Whereas delete[] is used to deallocate memory reserved for the array of the objects.

Delete[] operator prevents data leak, so it is a significant advantage of using delete[] in different conditions where it is required.

Hope this helps.

100 points
7 2