Re: why isn't there a placement delete syntax
kanze ha scritto:
Alberto Ganesh Barbati wrote:
andrew_nuss@yahoo.com ha scritto:
struct Object {
static void* operator new (Heap&, size_t);
static void operator delete (Heap&, void*);
};
Placement new is expected to store the additional info
somewhere, in particular in a place where operator delete can
obtain it using the only information it has, i.e.: the
pointer.
Note that this means that you cannot define a placement new
requiring a delete without also replacing global new and delete.
You have to replace global delete, since this is the delete
which will be called even for the objects allocated by placement
new. And you have to replace global new, because global new has
to work with global delete (and there's no way for your new
global delete to access the global delete it is replacing).
We are talking about per-class allocation and deallocation functions, so
global new/delete are not involved.
The most obvious way is to store the info in block itself, as
in (alignment issues omitted for brevity):
void* operator new (Heap& h, size_t n)
{
// alloc some more space to hold the extra info
void* ptr = h.alloc(n + sizeof(Heap*));
Heap* hptr = static_cast<Heap*>(ptr);
*hptr = &h; // store info in the block
return hptr + 1;
}
// placement delete used only when the constructor throws
void operator delete (Heap& h, void* ptr)
{
Heap* hptr = static_cast<Heap*>(ptr);
h.free(hptr - 1);
}
// regular delete, not placement!
void operator delete (void* ptr)
{
Heap* hptr = static_cast<Heap*>(ptr);
hptr[-1]->free(hptr - 1); // retrieve info from the block
}
And what happens when this delete is called for an object
allocated with non placement operator new?
That case can never occur because the class has a placement operator new
that inhibits the use of the non-placement syntax:
struct Object
{
static void* operator new(size_t n, Heap& h);
static void operator delete(void* p, Heap& h);
static void operator delete(void* p);
};
int main()
{
Object* o = new Object; // ill-formed
}
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]