Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there a special new and delete for arrays?

What is wrong with using delete instead of delete[]?

Is there something special happening under the covers for allocating and freeing arrays?

Why would it be different from malloc and free?

like image 415
JeffV Avatar asked Mar 18 '09 17:03

JeffV


2 Answers

The difference is that delete will only delete the entire memory range, but will only call the destructor for 1 object. delete[] will both delete the memory and call the destructor for every single object. If you do not use delete[] for arrays, it's only a matter of time before you introduce a resource leak into your application.

EDIT Update

According to the standard, passing an object allocated with new[] to delete is undefined. The likely behavior is that it will act as I described.

like image 199
JaredPar Avatar answered Sep 27 '22 23:09

JaredPar


Stroustrup talks about the reasons for separate new/new[] and delete/delete[]` operators in "The Design and Evolution of C++" in sections 10.3 through 10.5.1:

  • 10.3 Array Allocation - discusses that they wanted a way to allow arrays of objects to be allocated using a separate scheme from allocation single objects (ie., allocating arrays from a separate store). Adding the array versions of new and delete was a solution for this;
  • 10.5.1 Deallocating Arrays - discusses how a problem with deallocating arrays using just a single delete operator is that there needs to be more information than just the pointer in order to determine if the pointer points to the first element of an array or if it just points to a single object. Instead of "complicating the common case of allocating and deallocating individual objects", the delete[] operator is used to handle arrays. This fits in with the general C++ design philiosophy of "don't pay for what you don't use".

Whether this decision was a mistake or not is debatable - either way has good arguments, but we have what we have.

like image 28
Michael Burr Avatar answered Sep 27 '22 22:09

Michael Burr