Re: Implementing overloaded operator new[]/delete[]
On Sep 23, 11:38 pm, Tristan Wibberley <maihem-...@maihem.org> wrote:
On Sun, 2007-09-23 at 23:22 +0200, Alf P. Steinbach wrote:
* Tristan Wibberley:
Doesn't "delete ptr;" normally destroy all the elements of the array
before calling the overloaded operator delete[] in my class? How will=
it
know how many objects to destroy - does it keep a mapping of the
pointers I've returned from my operator new[] to the number of
elements/bytes that it asked my operator new[] to allocate?
You don't have to know or care. Your code is just asked to allocate a
certain number of bytes. How the allocated chunk of memory is used is
not the allocator or deallocator function's concern.
So I don't have to make any particular alignment guarantees, or
guarantee that a second call will be successful even if the first
allocation is deleted?
All operator new() functions are required to return memory that
is suitably aligned for all possible data types (or all data
types which would fit in the amount of memory allocated---I'm
not sure).
There is no formal requirement that operator delete() be
anything other than a no-op. The intent, and quality of
implementation considerations, of course, do suggest a little
more.
I just have to return a pointer to memory such that a pointer
to memory within the requested number of bytes following it
won't be returned by a subsequent call at least until the next
call of my operator delete[].
Are those the only requirements?
There's also alignment.
If so, then I can see why allocating things with new could be
slow - it will definitely need to use some mapping of the
pointers I've returned to the number of bytes it requested.
Most don't. There are all sorts of ways of recovering the
length.
This is independant of which operator new() you're implementing;
operator delete() is not passed the length, either, but just a
pointer.
In asking this I am in part looking for confirmation that
usage of overloading new[] and delete[] are either:
1) Usable only for wrapping global operator new with statistical records
or forcing failures as for unit tests,
2) Slow down as the number of current allocated blocks increases and
therefore something to avoid for all but allocation from limited pools
that starts throwing bad_alloc before the number of current blocks gets
large, or
3) Unspecified in general, essentially undefined behaviour
None of the above.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34