Preface: I'm optimizing an old codebase.
I have a class named Token
for which I added caching to for a subset of the tokens (but not all). Cached tokens may not be deleted as their pointers are stored in a permanent collection in memory for the whole lifetime of the program.
Unfortunately, the codebase has delete token
all over the place. So what I did was add a bool cached
member that is checked from inside Token::operator delete
and destructor ~Token()
, which returns from these respective functions immediately if cached
is true.
My question is, is this undefined behavior, or is it okay for me to do? Is it okay to execute the delete
operator on something that doesn't get deleted? Or will this bite me in the future?
class Token
{
bool cached;
void* data;
public:
~Token()
{
if (this->cached) return;
free(data);
}
void operator delete(void* p)
{
if (((Token*)p)->cached) return;
::operator delete(p);
}
// operator new, constructor etc.
}