Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C++ still have a delete[] AND a delete operator? [closed]

Is it hard to implement deletion of array using a single keyword? Is it less efficient?

like image 334
unj2 Avatar asked Jun 12 '12 15:06

unj2


1 Answers

First, let me summarize what both do: delete calls a destructor for one object and deallocates the memory; delete[] calls the destructor of some number of objects and deallocates the memory.

One could fold these into the same operation: "calls the destructor of some number of objects and deallocates the memory.". After all one is some number.

Both delete and delete[] operate on a pointer. Like this one:

foo* ptr;

Look at it closely. And tell me how many destructors should be called when we delete it. You can't. And so can't the compiler. This can only be known at runtime. The information about the number of objects has to be stored somewhere. That means that, for each usage of new[], there is some extra memory allocated to keep track of that number.

C++ is built on the principle of "you don't pay for what you don't use", and that's why the non-array forms exist: since delete always only deletes one object, new doesn't need to allocate any extra.

like image 160
R. Martinho Fernandes Avatar answered Sep 18 '22 13:09

R. Martinho Fernandes