Difference between delete and delete[] – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Sat, 05 Sep 2020 12:52:20 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg Difference between delete and delete[] – Programmerbay https://programmerbay.com 32 32 Difference between delete and delete[] https://programmerbay.com/difference-between-delete-and-delete/ https://programmerbay.com/difference-between-delete-and-delete/#respond Thu, 01 Aug 2019 19:30:15 +0000 https://www.programmerbay.com/?p=4425 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[]?

deletedelete[]
It is used to release the memory occupied by an object which is no longer neededIt 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 operatorIt frees memory held by an array of an object which allocated using new[]
It calls a class's destructor onceIt 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;

 

]]>
https://programmerbay.com/difference-between-delete-and-delete/feed/ 0