过程式析构:
测试案例:test.cpp
#include <iostream>
using namespace std;class Test
{
public:
Test(int dt=0){data=dt;}
~Test(){cout<<data<<endl;}
private:
int data;
};int w(void)
{
Test b(7);
Test c(8);
}int main(int argc,char **argv)
{
Test a(0);
if(1==1)
{Test a(1);Test b(2);}w();
if(1==1)
{Test a(3);Test b(4);}
Test c(5);
return 0;
}
程序结果:2 1 8 7 4 3 5 0
假设结论(析构时候顺序): 1.正序析构包含函数块 2.反序析构包含对象
对象式析构:
测试案例:test2.cpp
#include <iostream>
using namespace std;class Test
{
public:
Test(int dt=0){data=dt;cout<<data<<":construct"<<endl;}
~Test(){cout<<data<<":desctruct"<<endl;}
private:
int data;
};class Test2
{
public:
Test2(int dt=0):a(1),b(2){data=dt;}
~Test2(){cout<<data<<":Test2"<<endl;}
private:
int data;
Test a;
Test b;
static Test c;
static Test d;
};Test Test2::c(3);
Test Test2::d(4);int main(int argc,char **argv)
{
Test2 e;
return 0;
}
程序结果:
3:construct
4:construct
1:construct
2:construct
0:Test2
2:desctruct
1:desctruct
4:desctruct
3:desctruct
假设结论(析构顺序):先析构自己,再析构普通成员对象 定义的反序,再析构static对象 定义的反序