29.局部和全局重載new delete
阿新 • • 發佈:2018-03-12
end log eat sta 元素 void ati OS public
1 #include <iostream> 2 #include <Windows.h> 3 using namespace std; 4 5 //全局內存管理,統計釋放內存,分配內存 6 7 //重載全局的new 8 void *operator new(size_t size) 9 { 10 cout << "g_new call" << endl; 11 void *p = malloc(size); 12 return p; 13 } 14 15 //重載全局的delete 16 void operatordelete(void *p) 17 { 18 cout << "g_delete call" << endl; 19 free(p); 20 } 21 22 //重載全局的new[] 23 void *operator new [](size_t size) 24 { 25 cout << size << endl; 26 cout << "g_new call []" << endl; 27 return operator new(size);//每個元素調用一次new 28 } 2930 //重載全局的delete 31 void operator delete [](void *p) 32 { 33 cout << "g_delete [] call" << endl; 34 free(p); 35 } 36 37 class myclass 38 { 39 public: 40 myclass() 41 { 42 cout << "create call" << endl; 43 } 44 ~myclass() 45 { 46 cout << "delete call" << endl; 47 } 48 //局部重載new 49 static void * operator new(size_t size) 50 { 51 cout << "new call" << endl; 52 return malloc(size); 53 } 54 //局重載delete 55 static void operator delete(void *p) 56 { 57 ::delete p; 58 } 59 }; 60 61 void main() 62 { 63 //int *p = new int[3]{ 1,2,3 }; 64 //cout << p[1] << endl; 65 66 //myclass *p = new myclass; 67 //delete p; 68 69 //int *pint = new int[10]; 70 myclass *p1 = new myclass; 71 //delete p1; 72 73 cin.get(); 74 }
29.局部和全局重載new delete