#include #include //for malloc and free, exit, EXIT_SUCCESS, EXIT_FAILURE #include //for set_new_handler, bad_alloc #include "obj.h" using namespace std; void my_new_handler(); void *operator new(size_t n); //declaration for function in line 21 void operator delete(void *p); //declaration for function in line 39 int main() { set_new_handler(my_new_handler); const obj *const p = new obj(10); //calls operator new in line 21 delete p; //calls operator delete in line 39 return EXIT_SUCCESS; } void *operator new(size_t n) { void *p; //uninitialized variable while ((p = malloc(n)) == 0) { cerr << "operator new(" << n << ") out of store.\n"; if (void (*const f)() = set_new_handler(0)) { set_new_handler(f); (*f)(); //call the handler function } else { throw bad_alloc(); } } cout << "operator new(" << n << ") returns " << p << "\n"; return p; } void operator delete(void *p) { cout << "operator delete(" << p << ")\n"; free(p); } void my_new_handler() { cerr << "out of store\n"; exit(EXIT_FAILURE); }