重载operator new delete函数

Posted vlyf

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了重载operator new delete函数相关的知识,希望对你有一定的参考价值。

可以重载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函数的主要内容,如果未能解决你的问题,请参考以下文章

C++内存管理机制学习笔记:重载operate new/::operator new..../new()

C++内存管理机制学习笔记:重载operate new/::operator new..../new()

C++初阶:内存管理C/C++内存分布及管理方式 | new/delete实现原理及operator new和operator delete函数

C++初阶:内存管理C/C++内存分布及管理方式 | new/delete实现原理及operator new和operator delete函数

重载类的new和delete运算符成员函数

C++学习32 重载new和delete运算符