/*
* File: main.cpp
* Author: Vicky
*
*/
#include <cstddef>
#include <cstdlib>
#include <iostream>
class A{
public:
void* operator new(size_t size) {
std::cout << "分配大小:" << size << std::endl;
// return ::operator new(size);
return malloc(size);
}
void operator delete(void* p, size_t size) {
std::cout << "释放大小:" << size << std::endl;
// ::operator delete(p);
free(p);
}
private:
char name[20];
};
class A1 : public A{
public:
private:
char pswd[20];
};
// -----------------
class B{
public:
/** 虚析构函数的意义!!! */
virtual ~B(){
}
void* operator new(size_t size) {
std::cout << "分配大小:" << size << std::endl;
// return ::operator new(size);
return malloc(size);
}
void operator delete(void* p, size_t size) {
std::cout << "释放大小:" << size << std::endl;
// ::operator delete(p);
free(p);
}
private:
char name[20];
};
class B1 : public B{
public:
private:
char pswd[20];
};
/*
*
*/
int main(void) {
A* _a = new A();
delete _a;
A1* _a1 = new A1();
delete _a1;
std::cout << "---------------------------" << std::endl;
A* _a2 = new A1(); // 分配大小为40
delete _a2; // 释放大小却为20 (错误)
std::cout << "---------------------------" << std::endl;
B* _b1 = new B1(); // 分配大小为44
delete _b1; // 释放大小也为44 (正确)
return 0;
}
分配大小:20
释放大小:20
分配大小:40
释放大小:40
---------------------------
分配大小:40
释放大小:20
---------------------------
分配大小:44
释放大小:44
运行成功(总计时间: 125毫秒)
理解A* a = new A1();delete a; 编译器无法获得到正确的大小,在释放内存的时候,会安装类型获得大小,解决这个问题就需要使用虚析构函数。