Unlike Java, C++ doesn’t provide support for Garbage collector for cleaning of unreachable objects. In C++, a programmer who creates an object using new operator is also responsible for destroying that object manually after it is no longer needed. Negligence could lead to a memory leak which is nothing but a bunch of unreachable objects stacked up in heap memory. To handle this situation, one should delete the objects using delete or delete[] operator.
Don’t think destructor does the same job as delete. When delete statement is executed, just before, it triggers destructor of the respective class to which that object belongs to and release all the resources grabbed by it, and then after it frees the memory for reuse.
Difference between delete and delete[]?
delete | delete[] |
---|---|
It is used to release the memory occupied by an object which is no longer needed | It is used to get rid of an array's pointer and release the memory occupied by the array. |
It releases memory held by a single object which is allocated using new operator | It frees memory held by an array of an object which allocated using new[] |
It calls a class's destructor once | It calls as many destructors as the size of the array |
Syntax: delete objName; | Syntax: delete[] arrName; |
Simple example:
A *single = new A; A *many= new A[10]; delete single; delete[] many;