0 points
15 11 8

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 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[] 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.



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.

More Posts

Delete an element from an array C++. Lalit Kumar - Apr 26, 2020
How to clear an array in C++? Lalit Kumar - Jul 14, 2020
operator overloading in c++ using friend function Lalit Kumar - Oct 14, 2020
What Does -> Mean in C++? Lalit Kumar - Sep 6, 2020
No operator << matches these operands C++ Lalit Kumar - Sep 15, 2020
Deallocate memory using the delete operator in C++ Lalit Kumar - Jul 19, 2020
Convert char[] to string in C++ Lalit Kumar - Sep 19, 2020
Pass an 2D array to a function in C++ Lalit Kumar - Sep 15, 2020
Program to find the max value in the array with explanation in C++ Lalit Kumar - Sep 10, 2020
ISO forbids the variable length array in C++ Lalit Kumar - Sep 10, 2020