#include <iostream>
using namespace std;
class P {
int a; //4字节
public:
virtual ~P() { //父类的虚析构函数 //4字节
std::cout << "P destructor!" << std::endl;
}
};
class Child :public P {
int b; //4字节
public:
virtual ~Child() {//子类的虚析构函数
std::cout << "Child destructor!" << std::endl;
}
};
int main()
{
cout << sizeof(P) << endl;
cout << sizeof(Child) << endl;
P* p = new Child;
delete p;
return 0;
}
输出:
8
12
Child destructor!
P destructor!
内存模型:
1>virtualDestructor.cpp
1>class Child size(12):
1> ±–
1> 0 | ±-- (base class P)
1> 0 | | {vfptr}
1> 4 | | a
1> | + —
1> 8 | b
1> ±–
1>Child::[email protected]:
1> | &Child_meta
1> | 0
1> 0 | &Child::{dtor}