Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we even need the delete operator? (Can't we just use delete[])

Tags:

c++

pointers

I was reading about the delete and delete[] operators today and I can see that to free the memory allocated to myChar, I should call delete and to free memory for myCharArray I should use delete[].

However I have always thought of myChar as a pointer to an array of size 1. So why is it that we use delete in this case; and why do we need delete at all? Couldn't we have gotten away with using delete[] everywhere if myChar is effectively an array of size 1?

char* myChar = new char;
char* myCharArray = new char[5];

delete myChar;
delete[] myCharArray;
like image 839
AdaRaider Avatar asked Aug 22 '18 08:08

AdaRaider


2 Answers

A single object is not an array of size 1. An array of size 1, created with new char[1], needs to record the number of objects that were allocated, so that delete[] knows how many objects to destroy.

Arguably, new could be implemented internally as new[1] (and delete implemented as delete[]) - that would be a correct implementation. However, having separate new and new[1] allows the optimization of not storing the object count for single objects (a very common case).

The C++ principle of not paying for what you don't use comes into play here. If we create an array of objects, we pay the memory and processing price of storing the count, but if we create a single object, we don't incur the overhead.

like image 167
Toby Speight Avatar answered Nov 15 '22 10:11

Toby Speight


You're right that there's no inherent reason for the distinction between new/delete and new[]/delete[]; the language could have simply omitted the non-array version, or omitted delete and required delete[] to work correctly with a single object allocated by new. But doing that adds complexity and corresponding overhead to the implementation for the single-object case, since it would then have to store a size of 1 somewhere so that delete[] could do the right thing. One of the primary design principles of C++ was (and is) that you don't pay for what you don't use. new/delete is the result of this parsimony. It moves the cost from the implementation to the programmer.

like image 36
Pete Becker Avatar answered Nov 15 '22 12:11

Pete Becker