正文

不明所以的程序(C++析构函数)2007-12-03 16:42:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/lingdlz/31255.html

分享到:

不明所以的程序

请看下面的代码:

#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

阅读(2576) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册