Can override the global operator new delete function, details are as follows:
MyNewDelete.h
1 #pragma once 2 #include <stdlib.h> 3 #include <string> 4 #include <iostream> 5 using namespace std; 6 7 class Foo 8 { 9 public: 10 int id; 11 string str; 12 13 Foo() : id(0) { cout << "default ctor.this=" << this << "id=" << id << endl; } 14 Foo ( int I): ID (I) {COUT << " ctor.this = " << the this << " ID = " << ID << endl;} 15 16 // If the constructor for the virtual objects Fool a plurality of memory size of a pointer to the virtual memory pointers the vptr . 17 ~ Foo () {COUT << " dtor.this = " << the this << " ID = " << ID << endl;}; 18 is . 19 static void * operator new new (size_t size); // overloaded global operator new function; 20 static void operator Delete ( void * pdead, size_t size); // overloaded global operator delete function; 21 is static void * operator new new [] (size_t size); // overloaded global operator new [] function; 22 is static void operator Delete [] ( void * pdead, size_t size); // overloaded global operator delete [] function; 23 };
NewDelete.cpp
1 #include <iostream> 2 #include <ostream> 3 #include "MyNewDelete.h" 4 5 void *Foo::operator new(size_t size) 6 { 7 Foo *p = (Foo *)malloc(size); 8 cout << "Foo::operator new. size=" << size << " return " << p << endl; 9 return p; 10 } 11 12 void Foo::the deleteof operator (void *pdead, size_t size) 13 { 14 cout << "Foo::operator delete. size=" << size << " pdead= " << pdead << endl; 15 free(pdead); 16 } 17 18 void *Foo::operator new[](size_t size) 19 { 20 Foo *p = (Foo *)malloc(size * sizeof(Foo)); 21 cout << "Foo::operator new[]. size=" << size * sizeof(Foo) << " return " << p << endl; 22 return p; 23 } 24 25 void Foo::operator delete[](void *pdead, size_t size) 26 { 27 cout << "Foo::operator delete[]. size=" << size * sizeof(Foo) << " pdead= " << pdead << endl; 28 free(pdead); 29 } 30 31 int main() 32 { 33 is COUT << the sizeof (Foo) << endl; 34 is // if no call was members Globals 35 // call members 36 Foo * PF = new new Foo; 37 [ Delete PF; 38 is COUT << " ----- --------------------------------------------- " << endl; 39 // call Globals 40 // Foo new new Foo * PF = ::; 41 is // :: Delete PF; 42 is 43 is Foo * = P new new Foo ( . 7 ); 44 is delete p; 45 cout << "--------------------------------------------------" << endl; 46 Foo *pArray = new Foo[5]; 47 delete[] pArray; 48 49 return 0; 50 }