1、为啥重载
2、怎么重载
2.1 类的new和delete重载
class StudentA
{
public:
int name;
char age;
void* operator new(size_t size)
{
cout << "student new" << endl;
//void* p = new StudentA(); //递归了,死循环
void* p = :: new StudentA(); //正确
//void* p = malloc(size); //也可以使用malloc的c方法申请内存,防止递归循环
return p;
}
void operator delete(void* p)
{
cout << "student delete" << endl;
free(p);
}
};
int main()
{
StudentA* s = new StudentA();
delete s;
return 0;
}
参考:https://zhuanlan.zhihu.com/p/269251267
void* operator new(size_t size)
size_t size:为分配的内存的大小
void*:指向分配的内存的指针,这里为什么会返回一个如此泛泛的类型指针呢?我就返回确定的类型可不可以?可以试试。
2.2 new运算符重载,传入参数:
class StudentA
{
public:
int name;
char age;
void* operator new(size_t size, const char* filename, int line, const char* xxx, int a)
{
cout << xxx << endl;
cout << a << endl;
return ::operator new(size);
}
};
#define xxxx new(__FILE__ , __LINE__, "abc", 12)
int main()
{
StudentA* s = xxxx StudentA;
delete s;
return 0;
}
new的第一个参数必须是size_t类型。后面的参数,可以是任意的。比如我们上面的传入的文件名、行号、abc、12四个参数。