overloading new/delete

Brammie picture Brammie · Feb 24, 2009 · Viewed 76.2k times · Source

I'm making a little memory leak finder in my program, but my way of overloading new and delete (and also new[] and delete[]) doesn't seem to do anything.

void* operator new (unsigned int size, const char* filename, int line)
{
    void* ptr = new void[size];
    memleakfinder.AddTrack(ptr,size,filename,line);
    return ptr;
}

The way I overloaded new is shown in the code snippet above. I guess it's something with the operator returning void* but I do not know what to do about it.

Answer

Dan picture Dan · Aug 10, 2011

Never ever try to overload new/delete globally

Why is it whenever someone tries to use a less common feature of C++, someone acts like it should never be done?

It's done all the time, it is quite common, and I have not worked for a company that did not do this.

Globally overloaded new and delete are extremely helpful in tracking memory, memory bugs, buffer overruns, etc.

Nobody in their right mind is going to go through a program with several million lines of code, and add a new and delete member to each and every class. That's just stupid.