对象的是怎么死的?

王朝other·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

一个对象构造了后,系统构造了后析构与否与编译器有关?

今天复习了C++语言,编了一个小程序。发现一个在对象构造了后,在VC6下面系统会自己调用该类的析构寒暑,而在Dev-C++(使用gcc)下面就不会调用?另外,如果建立的是对象的指针,那么系统是不会自己调用析构函数的。

代码如下:

#include

using namespace std;

class Counter

{

private:

int elem;

public:

Counter();

Counter(int elem);

~Counter();

};

static int counter;

Counter::Counter()

{

elem = 0;

counter++;

cout<<"in Counter()"<

<endl;

cout<<"counter = "<<endl;

}

Counter::Counter(int arg)

{

elem = arg;

counter++;

cout<<"in Counter(int)"<<endl

cout<<"counter = "<<endl;

}

Counter::~Counter()

{

counter--;

cout<<"in ~Counter()"<<endl;

cout<<"counter = "<<endl;

}

int main(int argc, char *argv[])

{

Counter c1;

Counter c2;

Counter c3;

Counter *cp = new Counter(10);

cp->~Counter();

return 0;

}

在VC6下的运行结果是:

in Counter()

counter = 1

in Counter()

counter = 2

in Counter()

counter = 3

in Counter(int)

counter = 4

in ~Counter()

counter = 3

in ~Counter()

counter = 2

in ~Counter()

counter = 1

in ~Counter()

counter = 0

Press any key to continue

而在Dev-C++种结果为:

in Counter()

counter = 1

in Counter()

counter = 2

in Counter()

counter = 3

in Counter(int)

counter = 4

in ~Counter()

counter = 3

Press any key to continue . . .

=================================

结论:

在对象的销毁阶段,是否调用析构函数,始于编译器有关的,而不是由语言定义的。所以在实际编程中,这一点对对象生命周期的控制的理解非常实用。:-)

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航