Re: How to use parameter in operator delete?
On 06.07.12 03.42, Nephi Immortal wrote:
I implement operator new and operator delete by adding an extra parameter. If I want to implement one heap class and create more than one heap object, then both operator new and operator delete are able to select correct heap object. How can I do that?
For operator new this is straight forward, as you have seen.
For operator delete the important question is in which heap is the
object to be deleted and where do you get this information from. You do
not want to do this manually, i.e. by passing the (hopefully) correct
heap to operator delete. This would be very error prone.
The heap needs to be tied to the object at the invocation of operator
new. You could do this intrusive or non-intrusive.
You eliminated the intrusive Version with class individual new/delete
operators already.
So the non-intrusive version is left:
class Heap
{public:
void* allocate(size_t size);
void free(void*);
};
void* operator new(size_t size, Heap& heap)
{ Heap** ptr = heap.allocate(size + sizeof(Heap*));
*ptr = &heap;
return ptr + 1;
}
void* operator new(size_t size)
{ Heap** ptr = (Heap**)std::malloc(size + sizeof(Heap*));
*ptr = NULL;
return ptr + 1;
}
void operator delete(void* p)
{ Heap** hp = (Heap**)p;
if (*hp)
(*hp)->free(hp);
else
std::free(hp);
}
Optionally the same for new[]/delete[].
The price of the non-intrusive solution is that /every/ allocation takes
space for an additional pointer. Unless you have an embedded environment
with low memory this should not cause much concern.
I do not want to create operator new and operator delete inside class body. It is independent to work with all types.
A common base class could do the job.
Marcel