码迷,mamicode.com
首页 > 其他好文 > 详细

重载operator new delete函数

时间:2019-10-18 18:43:50      阅读:71      评论:0      收藏:0      [点我收藏+]

标签: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 }

 

重载operator new delete函数

标签:bsp   rtu   his   ring   col   dea   Once   lib   default   

原文地址:https://www.cnblogs.com/vlyf/p/11699932.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!