不明所以的程序
请看下面的代码:
#include <iostream>
using namespace std;
class Test{
public:
Test(){ cout<<this<<" construct\n"; }
~Test(){ cout<<this<<" deastruct\n"; }
};
Test global;
int main(){
Test local;
cout<<"local variable: "<<&local<<endl;
cout<<"global variable: "<<&global<<endl;
return EXIT_SUCCESS;
}
/// 输出结果如下
0047CDF8 construct
0012FF70 construct
local variable: 0012FF70
global variable: 0047CDF8
0012FF70 deastruct
Press any key to continue
从输出结果可以知道全局变量的析构函数没有被调用
再看下面的代码:
#include <iostream>
using namespace std;
class Test{
public:
Test(){ printf("%x construct\n",this); }
~Test(){ printf("%x deastruct\n",this); }
};
Test global;
int main(){
Test local;
printf("local variable: %x\n",&local);
printf("global variable: %x\n",&global);
return EXIT_SUCCESS;
}
//// 输出结果
4384a8 construct
12ff7c construct
local variable: 12ff7c
global variable: 4384a8
12ff7c deastruct
4384a8 deastruct
Press any key to continue
两个对象的析构函数均被调用,不同之处仅是输出函数,不知道是什么原因,正常情况下程序结束时,每个对象的析构函数是应该被调用的,有知道为什么的请留言解释下。
平台 : VC++6.0 + WIN 2000
评论