When I allocate a dynamic array in C++ (T * p = new T[n]
), I use delete [] p to free the allocated memory. Obviously, the system knows the array size (in order among other things to call n times T's destructor). This is discussed elsewhere. For instance How does delete[] “know” the size of the operand array?. This is implemenation details.
But why was it not decided to make this information available?
Thx
When you allocate memory on the heap, your allocator will keep track of how much memory you have allocated. This is usually stored in a "head" segment just before the memory that you get allocated. That way when it's time to free the memory, the de-allocator knows exactly how much memory to free.
Deleting array elements When the delete operator removes an array element, that element is no longer in the array.
But in C++, delete[] is an operator with a very specific behavior: An expression with the delete[] operator, first calls the appropriate destructors for each element in the array (if these are of a class type), and then calls an array deallocation function.
Usually operator new allocates a memory block with some invisible for the user header that contains the size of the allocated block. free the memory, the de-allocator knows exactly how much memory to free. The delete operator just randomly selects memory cells for erasure.
delete[]
might not necessarily know the exact array size. It might over-allocate for example, or do something else entirely bizarre yet conformant with the standard.
Facetiously the answer could also be on the lines that nobody has managed to convince the standards committee of the merits of the idea; perhaps sizeof[](p)
could be the proposed syntax? sizeof
is already a keyword, already has a runtime-evaluable flavour in C so it's not an enormous leap to envisage an equivalent in C++, and my []
distinguishes from sizeof(pointer type)
.
It would inhibit optimisations where knowledge of array size is not nessesary:
int* foo = new int[...];
. . .
delete[] foo;
As int
is a trivial type and does not have a destructor, compiler do not need to know how many int
s are there. Even if it is an array of 1 int in 4 MB memory chunk.
const MyType* const foo = new MyType[. . .];
. . .
delete[] foo;
Here compiler knows size of the array, pointed by foo, and it knows, that it cannot change legally. So it just can use that information directly, and do not store amount of items in allocated array.
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