It’s a follow on from the fundamental rule of “don’t pay for what you don’t need”. In your example delete[] a; doesn’t need to know the size of the array, because int doesn’t have a destructor. If you had written:
std::string* a;
a = new std::string[n];
...
delete [] a;
Then the delete has to call destructors (and needs to know how many to call) – in which case the new has to save that count. However, given it doesn’t need to be saved on all occasions, Bjarne decided not to give access to it.
(In hindsight, I think this was a mistake …)
Even with int of course, something has to know about the size of the allocated memory, but:
-
Many allocators round up the size to some convenient multiple (say 64 bytes) for alignment and convenience reasons. The allocator knows that a block is 64 bytes long – but it doesn’t know whether that is because
nwas 1 … or 16. -
The C++ run-time library may not have access to the size of the allocated block. If for example,
newanddeleteare usingmallocandfreeunder the hood, then the C++ library has no way to know the size of a block returned bymalloc. (Usually of course,newandmallocare both part of the same library – but not always.)