一 new 内存分配细节探秘
我们以分配10个char为例,说明,观察内存发现,当delete 的时候,实际上很多内存都改变了。
实际上 new 内存不是一个简单的事情。为了记录和管理分配出去的内存,额外分配了不少内存,造成了浪费。尤其是多次申请小块的内存,浪费更严重。
不同的编译器对于这块实现是不同的。
但是功能都是大同小异的,要管理 分配出去的内存,考虑效率等。
二 重载类中的 operator new 和 operator delete 操作符
前提
从前面的知识我们知道:当你new Teacher后,主要代码逻辑如下:
Teacher *ptea = new Teacher;
operator new();
malloc();
Teacher::Teacher();
-----------------------------------------
delete ptea;
Teacher::~Teacher();
operator delete();
free();
思路
我们这里就是要重写operator new()方法,C++编译器在operator new()方法中调用了 malloc()方法分配内存。因此我们重写时也需要malloc内存。
我们这里就是要重写operator delete()方法,C++编译器在operator delete()方法中调用了 free()释放内存。因此我们重写时也需要free内存。
写法
static void* operator new(size_t size) {
Teacher35* ppoint = (Teacher35 *)malloc(size);
return ppoint;
}
static void operator delete(void *phead) {
free(phead);
}
class Teacher35 {
public:
Teacher35() {
cout << "Teacher35 gouzao fangfa " << endl;//3
}
~Teacher35() {
cout << "Teacher35 xigou" << endl;//5
}
//static void* operator new(size_t size) {
// Teacher35* ppoint = (Teacher35 *)malloc(size);//2. 在teacher35有一个int的时候,size是4
// return ppoint;
//}
//static void operator delete(void *phead) {
// free(phead);//6
//}
static void* operator new(size_t size);
static void operator delete(void *phead);
int mage;
};
void* Teacher35::operator new(size_t size) {
Teacher35* ppoint = (Teacher35 *)malloc(size);
return ppoint;
}
void Teacher35::operator delete(void *phead) {
free(phead);
}
void main() {
Teacher35 *ptea = new Teacher35; //1
cout << "111" << endl;
delete ptea; //4
cout << "222" << endl;
}
三 重载类中的 operator new[] 和 operator delete[] 操作符
class Teacher35 {
public:
Teacher35() {
cout << "Teacher35 gouzao fangfa " << endl;//3
}
~Teacher35() {
cout << "Teacher35 xigou" << endl;//5
}
static void* operator new(size_t size) {
Teacher35* ppoint = (Teacher35 *)malloc(size);//2. 在teacher35有一个int的时候,size是4
return ppoint;
}
static void operator delete(void *phead) {
free(phead);//6
}
//static void* operator new(size_t size);
//static void operator delete(void *phead);
static void* operator new[](size_t size) {
Teacher35* ppoint = (Teacher35 *)malloc(size);//2. 在teacher35[3]的时候,加上4个字节,这4个字节 存储的是3,因此 size 大小是 3个teacher的大小 = 3*sizeof(Teacher)+ 4个字节 记录几个teacher(也就是3)
return ppoint;
}
static void operator delete[](void *phead) {
free(phead);//6
}
int mage;
};
//void* Teacher35::operator new(size_t size) {
// Teacher35* ppoint = (Teacher35 *)malloc(size);
// return ppoint;
//}
//
//void Teacher35::operator delete(void *phead) {
// free(phead);
//}
void main() {
//Teacher35 *ptea = new Teacher35; //1
//cout << "111" << endl;
//delete ptea; //4
//cout << "222" << endl;
Teacher35 *ptea = new Teacher35[3];
delete[] ptea;
}