标签:
#include <iostream> using namespace std; //new 的本质还是malloc delete 的本质是free //delete new 最底层就是free malloc //delete new 提供了重载的机制(官方说法),通俗的理解就是劫持 //delete new 全局重载,只要分配内存都劫持 //内存防泄漏系统,内存反复释放,进制创建,禁止销毁 //delete new 局部重载,只影响本类型,只要分配内存就劫持 //内存防泄漏系统,内存反复释放,进制创建,禁止销毁 int num = 0; void *operator new(size_t size)//全局重载, { num += 1;//计数 if (size == 0) { return nullptr; } void *p = malloc(size); cout << "全局new call" << endl; return p; } void *operator new[](size_t size)//[]数组 { cout << "全局 new[] call " << endl; return operator new(size); } void operator delete(void *p)//监测内存释放的过程 { num -= 1; cout << "全局delete call" << endl; free(p); } void operator delete[](void *p)//批量释放 { cout << "全局 delete[] call" << endl; operator delete(p); } class myclass { public: int data; void *operator new(size_t size)//局部重载 { cout << "mycalss new call" << endl; myclass *p = ::new myclass;//::使用全局的new return p; } void operator delete(void *p) { cout << "myclass delete call" << endl; ::delete p; free(p); } protected: private: }; void main1() { int *p1 = new int; int *p2 = new int; int *p3 = new int; int *p4 = new int; myclass *p = new myclass; cout << num << endl; delete p1; delete p2; cout << num << endl; system("pause"); //全局new call //全局new call //全局new call //全局new call //mycalss new call //全局new call //5 //全局delete call //全局delete call //3 } class newclass { public: newclass() { cout << "new class Create" << endl; } ~newclass() { cout << "newclass Delete" << endl; } int data; void *operator new(size_t size) { cout << "newclass new call" << endl; newclass *p = ::new newclass;//::使用全局的new return p; } void operator delete(void *p) { cout << "newclass delete call" << endl; ::delete p; free(p); } protected: private: }; void main2() { newclass *p = new newclass; delete p; cin.get(); system("pause"); } //newclass new call //全局new call //new class Create //new class Create //newclass Delete //newclass delete call //全局delete call void main() { int *p = new int[10]; //delete p;//对于基本数据类型,有无[]都没关系,但是建议写上[] delete [] p; system("pause"); } //全局 new[] call //全局new call //全局delete call void main4() { newclass *p = new newclass; delete[]p;//delete必须加[] 必须批量释放数组,调用每一个元素析构函数 cin.get(); }
标签:
原文地址:http://blog.csdn.net/varygod/article/details/45649447