C++ 中重载new 与delete
类中重载new与delete
类中重载new与delete的语法如下
void* operator new(size_t size);
void operator delete(void*);
完整代码示例如下
#include<iostream>
#include<stdlib.h>
using namespace std;
class student
{
string name;
int age;
public:
student()
{
cout<< "Constructor is called\n" ;
}
student(string name, int age)
{
this->name = name;
this->age = age;
}
void display()
{
cout<< "Name:" << name << endl;
cout<< "Age:" << age << endl;
}
void * operator new(size_t size)
{
cout<< "Overloading new operator with size: " << size << endl;
void * p = malloc(size);
return p;
}
void operator delete(void * p)
{
cout<< "Overloading delete operator " << endl;
free(p);
}
};
int main()
{
student * p = new student("Yash", 24);
p->display();
delete p;
}
输出结果
Overloading new operator with size: 40
Name:Yash
Age:24
Overloading delete operator
全局重载new 与delete
全局的重载与类中重载语法一样
#include<iostream>
#include<stdlib.h>
using namespace std;
void * operator new(size_t size)
{
cout << "New operator overloading " << endl;
void * p = malloc(size);
return p;
}
void operator delete(void * p)
{
cout << "Delete operator overloading " << endl;
free(p);
}
int main()
{
int n = 5, i;
int * p = new int[3];
for (i = 0; i<n; i++)
p[i]= i;
cout << "Array: ";
for(i = 0; i<n; i++)
cout << p[i] << " ";
cout << endl;
delete [] p;
}
输出
New operator overloading
Array: 0 1 2 3 4
Delete operator overloading
带参数的new重载
类的重载和全局的重载都可以带参数。
void *operator new(size_t size, 类型 类型变量名,....)
这里要求第一个变量为size_t size ,后面的变量数量可以变化
示例如下
void *operator new(size_t size, char c)
{
void *ptr;
ptr = malloc(size);
if (ptr!=NULL)
*ptr = c;
return ptr;
}
main()
{
char *ch = new('#') char; //带参数new的使用方法
}
这里要注意的是delete 带参数的重载,不能手动调用,如下
void* operator new(size_t size, int x)
{
cout<<" x = "<<x<<endl;
return malloc(size);
}
void operator delete(void* p, int x)
{
cout<<" x = "<<x<<endl;
free(p);
}
A* p = new(3) A;//ok
delete(3) p;//error C2541: “delete”: 不能删除不是指针的对象
重载的delete只有当自定义的new发生异常时才被调用。
重载new与delete的原因
- 常用的原因是分析内存泄露,程序异常报错。
- 有时希望delete时执行一些特定的操作,比如编译器默认的delete虽然释放了这部分的内存,但释放的这部分的内存数据还在,想在释放时用0覆盖已经释放的内存,提高应用程序数据的安全性,这时需要重载delete
- 某些场景下能提高性能。例如通过重载new与delete 自己管理底层的内存,而不是编译器new时每次都从堆分配(或者重复利用前面创建的内存)。
使用
新建cpp,h文件,参考编译即可使用自定义的new与delete