Problem with placement operator delete []
I was trying to implement placement new and delete in my applicaiton
as follows,
class A{
int i;
public:
void * operator new[] (size_t size, Allocator alloc)
{ return alloc.Alloc(size); }
void operator delete[] (void *ptr, Allocator alloc)
{ alloc.Free(ptr); }
};
class B {
Allocator &alloc;
A *ap;
public:
B(Allocator a) : alloc(a)
{
ap = new(alloc) A[50];
....
}
~B() {
// Since there is no way to call placement delete explicitly I have
to do this
A::operator delete[] (ap, alloc);
}
}
Now the problem is, the placement new[] gets "size" as (sizeof(A) *50
+ 4) the extra 4 bytes are added by the compiler for keeping track of
the array dimension (i.e 50). Which means alloc.Alloc() actually
allocates 204 bytes. Suppose the pointer which Alloc returned is
0x000100, Now compiler automatically adjusts it to 0x000104 to offset
those extra 4 bytes and "ap" gets a value 0x000104.
Now when I call placement delete[] directly then I pass 0x000104 to
Free, but actually I should pass 0x000100. But for this I will have to
subtract those 4 bytes from "ap".
But I think that a very bad solution, Is there any better way to call
placement delete[] so that we don't have to take care of the above
mentioned 4 byte adjustment.
Regards