Why is it undefined behavior to delete[] an array of derived objects via a base pointer?

Base* p = new Base[n] creates an n-sized array of Base elements, of which p then points to the first element. Base* p = new Derived[n] however, creates an n-sized array of Derived elements. p then points to the Base subobject of the first element. p does not however refer to the first element of the array, which is what a valid delete[] p expression requires.

Of course it would be possible to mandate (and then implement) that delete [] p Does The Right Thing™ in this case. But what would it take? An implementation would have to take care to somehow retrieve the element type of the array, and then morally dynamic_cast p to this type. Then it’s a matter of doing a plain delete[] like we already do.

The problem with that is that this would be needed every time an array of polymorphic element type, regardless of whether the polymorphism is used on not. In my opinion, this doesn’t fit with the C++ philosophy of not paying for what you don’t use. But worse: a polymorphic-enabled delete[] p is simply useless because p is almost useless in your question. p is a pointer to a subobject of an element and no more; it’s otherwise completely unrelated to the array. You certainly can’t do p[i] (for i > 0) with it. So it’s not unreasonable that delete[] p doesn’t work.

To sum up:

  • arrays already have plenty of legitimate uses. By not allowing arrays to behave polymorphically (either as a whole or only for delete[]) this means that arrays with a polymorphic element type are not penalized for those legitimate uses, which is in line with the philosophy of C++.

  • if on the other hand an array with polymorphic behaviour is needed, it’s possible to implement one in terms of what we have already.

Leave a Comment