I want to override delete operator in my class. Here\'s what I am trying to do,but not succeeding.
class Complex{
void *operator new(size_t
Deleting through delete is quite strange, but deleting a void*
is UB.
Also, size_t
is not a built-in type: it is define in
.
This can be fine:
#include
class Complex
{
void *operator new(size_t s);
void operator delete(void *ptr);
};
void* Complex::operator new(size_t s)
{ return new char[s]; } //allocate a buffer of s bytes
void Complex::operator delete(void *ptr)
{ delete[] static_cast(ptr); } //deallocate the buffer
Practically, we allocate/deallocate a buffer of appropriate size coherently in new / delete.
In new
, we ask the system to give us the bytes we need. I used char[s]
since char
is the unit of memory size_t
measures: sizeof(char) == 1
by definition.
In delete
we have to give back to the system the bytes identified by ptr
.
Since we allocated them as char[]
, we have to delete them as char[]
, hence the use of delete[]
and the cast to char*
.