Is it hard to implement deletion of array using a single keyword? Is it less efficient?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With