Re: retrieve size of array
polushin@gmail.com (Andrei Polushin) wrote (abridged):
In particular, if the allocator knows the size of the allocated block,
why does compiler need to overallocate arrays to store the size twice?
Because the compiler is constrained to new/delete interface from the
allocator, which is rather weak for this case.
No, it's because the size of the array may not deducible from the size of
the block. This is because the allocator may have a minimum block size it
can handle, and it may need its block sizes to be a multiple of some
number.
Deduction in the other direction is often possible, because applying the
minimum size and rounding up is deterministic. It would be feasible for
the C++ compiler to always store the size of the array, and make this
available both upwards to the application and downwards to the allocator.
Then in many cases the allocator wouldn't need to store its own size, and
neither would the application. For objects that have destructors, the
compiler needs to store the array size anyway so there would be no
overhead. The size would be stored exactly once.
Currently if the objects don't have destructors the compiler is allowed to
not store the array size, and this means if the allocator needs the size
it has to store it itself. Likewise for the application. So in practice
the size is effectively stored 3 times over. Which is silly.
The only downside to the compiler always storing the array size is if (a)
the object has no destructor; (b) the allocator doesn't use it (eg with
arena-based schemes); and (c) the application doesn't need it either. I
suspect this is rare enough that it is acceptable to have the programmer
optimise it as a special case, without using new[].
That's not how C++ is. Not only is there no way for applications to get
the array size, but global operator() does not take a size argument so the
allocator can't get it either. I suspect this is partly because the
designers were copying malloc/free, and free() doesn't take a size
argument. Also I expect the early implementations of operator delete()
were layered on top of free() and so could not use a size argument.
Malloc/free is going to store its own size regardless.
It's a shame. Another issue is that new[]/delete[] don't offer any way to
resize an allocation in-place.
-- Dave Harris, Nottingham, UK.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]