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 s);
void operator delete(void *ptr);
};
void Complex::operator delete(void *ptr){
delete ptr;
}
I get the error:
deleting void* is undefined
Your declarations are correct. The problem is in the code that implements your
operator delete
: it uses the keyworddelete
instead of calling the globaloperator delete
. Write it like this:That's assuming that your
operator new
used the globaloperator new
.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<cstddef>
.This can be fine:
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 usedchar[s]
sincechar
is the unit of memorysize_t
measures:sizeof(char) == 1
by definition.In
delete
we have to give back to the system the bytes identified byptr
. Since we allocated them aschar[]
, we have to delete them aschar[]
, hence the use ofdelete[]
and the cast tochar*
.As the error message indicates, you can't
delete
avoid*
. Try this: