C++ new delete new[] delete[]重载实现

篇博文主要是分析了C++ new()和构造函数的执行,delete()与析构函数的调用方式,通过全局重载和局部重载看清楚调用的关系

[cpp]  view plain  copy
  1. using namespace std;  
  2. #include <iostream>  
  3. #include <cstdlib>  
  4.   
  5. class Student{  
  6.   
  7. public:  
  8.   
  9.     Student(){  
  10.         cout <<  "Constructer" << endl;  
  11.     }  
  12.   
  13.     ~Student(){  
  14.         cout << "析构函数" << endl;  
  15.     }  
  16.   
  17.     static void* operator new(size_t size){  
  18.         cout << "own new function" << endl;  
  19.         Student* stu = (Student*)::operator new(size);  
  20.         return stu;  
  21.   
  22.     }  
  23.   
  24.     static void operator delete(void* p){  
  25.         cout << "own delete function" << endl;  
  26.         ::delete p;  
  27.     }  
  28.   
  29.     static void* operator new[](size_t size){  
  30.         cout <<  "own new[] function" <<endl;  
  31.         return ::operator new(size);  
  32.     }  
  33.      
  34. };  
  35.   
  36.   
  37. void* operator new(size_t size){  
  38.     cout << "global new function" << endl;  
  39.     void* p = malloc(size);  
  40.     return p;  
  41. }  
  42.   
  43.   
  44. void operator delete(void * p){  
  45.     cout << "global delete function"<< endl;  
  46.     free(p);  
  47. }  
  48.   
  49. void operator delete[](void* p){  
  50.     cout << "global delete[] function" << endl;  
  51.     free(p);  
  52. }  
  53.   
  54. void main(){  
  55.   
  56.     Student* student = new Student();  
  57.     delete student;  
  58.   
  59.     //Student* student2 = new Student[5];  
  60.     //delete[] student2;  
  61.   
  62.     cin.get();  
  63. }  


可以看出执行顺序为:内部重载的new-->全局重载的new()--->malloc()-->构造函数初始化-->内部的析构函数---》内部的delete()--》全局的delete()-->free()函数

猜你喜欢

转载自blog.csdn.net/linuxheik/article/details/80448242