标签:bsp rtu his ring col dea Once lib default
可以重载global的operator new delete 函数,细节如下:
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=" << this << "id=" << id << endl; } 15 16 //若构造函数为virtual 则Fool对象会多一个指针大小的内存用来存虚指针vptr 17 ~Foo() { cout << "dtor.this=" << this << "id=" << id << endl; }; 18 19 static void *operator new(size_t size); //重载全局operator new 函数; 20 static void operator delete(void *pdead, size_t size); //重载全局operator delete函数; 21 static void *operator new[](size_t size); //重载全局operator new[]函数; 22 static void operator delete[](void *pdead, size_t size); //重载全局operator delete[]函数; 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::operator delete(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 cout << sizeof(Foo) << endl; 34 //若无members 才调用globals 35 //调用members 36 Foo *pf = new Foo; 37 delete pf; 38 cout << "--------------------------------------------------" << endl; 39 //调用globals 40 //Foo *pf = ::new Foo; 41 //::delete pf; 42 43 Foo *p = new Foo(7); 44 delete p; 45 cout << "--------------------------------------------------" << endl; 46 Foo *pArray = new Foo[5]; 47 delete[] pArray; 48 49 return 0; 50 }
标签:bsp rtu his ring col dea Once lib default
原文地址:https://www.cnblogs.com/vlyf/p/11699932.html