You may define your own new operator or allocation function as a class member
function or a global namespace function with the following restrictions:
You may define your own delete operator or deallocation function as a class member function or a global namespace function with the following restrictions:
The following example defines replacement functions for global namespace new and delete:
#include <cstdio> #include <cstdlib> using namespace std; void* operator new(size_t sz) { printf("operator new with %d bytes\n", sz); void* p = malloc(sz); if (p == 0) printf("Memory error\n"); return p; } void operator delete(void* p) { if (p == 0) printf ("Deleting a null pointer\n"); else { printf("delete object\n"); free(p); } } struct A { const char* data; A() : data("Text String") { printf("Constructor of S\n"); } ~A() { printf("Destructor of S\n"); } }; int main() { A* ap1 = new A; delete ap1; printf("Array of size 2:\n"); A* ap2 = new A[2]; delete[] ap2; }
The following is the output of the above example:
operator new with 40 bytes operator new with 33 bytes operator new with 4 bytes Constructor of S Destructor of S delete object Array of size 2: operator new with 16 bytes Constructor of S Constructor of S Destructor of S Destructor of S delete object
Related References