Search code examples
c++memory-managementlanguage-designdelete-operator

Why *must* delete[] and delete be different?


I'm well aware that in C++, what delete[] is to new[], delete is to new. This is not about C++ syntax. I am wondering about the reasons delete[] was defined as something distinct from the plain delete. What are the implementation reasons for this?

Consider what happens with this code:

MyClass *object = new MyClass;
delete object;

When delete is encountered the memory manager has to lookup the object pointer value in its allocation structure, whatever it is, and mark the corresponding sizeof(MyClass) chunk of memory as free.

Now consider what happens with this code:

MyClass *array = new MyClass[ num_objects ];
delete [] array;

When delete is encountered the memory manager has to lookup the array pointer value in its allocation structure, whatever it is, find num_objects value from that structure , and mark the corresponding num_objects*sizeof(MyClass) chunk of memory as free.

Apart from num_objects being assumed 1 in the single object case and looked up in the internal data structure in the array case I don't see the difference. So why delete and delete[] couldn't have been spelled identically?

In other words, what's wrong with

MyClass *object = new MyClass;

being implemented as

MyClass *object = new MyClass[1];

so that C++ syntax wouldn't have to make distinction between delete and delete[] ?


Solution

  • In principle, these could be implemented in the same way. However, there's a cost to storing the number of elements somewhere, iterating over those elements, and calling the destructor on each (both in terms of time and in terms of space.)

    One of the core philosophies of C++ is "don't pay for what you don't use." Since there is an extra cost associated with the array-based allocation and deallocation routines that programmers might not want to pay for, the language explicitly makes the two operations separate.