CSDN博客

img iden

对象的是怎么死的?

发表于2004/7/16 13:45:00  749人阅读

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

今天复习了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 . . .

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

结论:

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

0 0

相关博文

我的热门文章

img
取 消
img