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 operator delete(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 } 29 30 //重载全局的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 }
原文地址:https://www.cnblogs.com/xiaochi/p/8546904.html
时间: 2024-10-29 13:05:17