I have overloaded new and delete operators. I want to save pointers to ‘old’ new and delete to call it into ‘new’ new and delete. For example:
#include "h.h"
void * operator new ( size_t size, /*args*/ ) throw (std::bad_alloc)
{
void * p = 0;
p = original_new(size); //calling for 'old' new
//some code
return p;
}
And the similar operator delete.
So, I’m trying in my header file to type the following:
static void * (*original_new)(size_t) = ::operator new;
static void * (*original_new_arr)(size_t) = ::operator new[];
static void (*original_delete)(void *) = ::operator delete;
static void (*original_delete_arr)(void *) = ::operator delete[];
It is successfully compiled, but I have core dump on start.
It is possible to call malloc in new bad it is really bad idea. It is possible to call new(std::nothrow) but it is bad too.
You don’t need to save pointers; defining a placement new operator (any
operator newfunction which takes more than one argument) doesn’tremove the existing operators; it just overloads them. To call the
standard operator new function from a placement operator new function:
Note that you do not want to do this if your placement new returns
anything but the exact address returned by
::operator new. Otherwise,deletewon’t work. If you use any placement new that return anythingother than a pointer returned by
::operator new, you need to define anew global
operator delete(because this is the one that will becalled), which in turn means that you have to define a new standard
operator newas well, so that it will work correctly with your newoperator delete. In order to avoid having to implement all of thememory management yourself, use
mallocandfreein yourimplementations.