Re: How to use parameter in operator delete?
On 7/5/2012 9:42 PM, Nephi Immortal wrote:
class Heap
{
public:
Heap() {}
void run() {}
};
void* operator new(
size_t size,
Heap& heap
)
{
heap.run();
return 0;
}
void operator delete(
void* p,
Heap& heap
)
While your compiler allows you to define this form, you can't call it
directly. There is no syntax for that.
{
heap.run();
}
int main()
{
Heap heap;
char* byte = new( heap ) char;
delete( heap ) byte; // ? does not compile -- how?
There is no "placement delete". The special operator delete can only be
defined to be called by the compiler in case the constructor that was
called in the placement new form throws an exception.
return 0;
}
You can't pass an unrelated object to the operator delete function. You
will only pass your object to the operator delete function that has been
defined in the class of that object, not the global one. If you can
live with your own global heap, though, this works:
#include <iostream>
#include <cstdlib>
class Heap
{
public:
Heap() {}
void run(void* p = 0) {
std::cout << "Heap::run was called with p=" << p << "\n";
}
};
Heap heap;
void* operator new(
size_t size,
Heap& heap
)
{
heap.run();
return std::malloc(size);
}
void operator delete(
void* p)
{
heap.run(p);
std::free(p);
}
int main()
{
char* byte = new( heap ) char;
delete byte;
return 0;
}
V
--
I do not respond to top-posted replies, please don't ask