2

I have such code:

#include <iostream>

using namespace std;

class X
{
    int a;
public:
    X()
    {
        cout<<"X constructor was called"<<endl;
    }
    X(int n)
    {
        cout<<"X(int) constructor was called"<<endl;
    }
    ~X(){cout<<"X dectructor was called"<<endl;}
};
int main()
{
    X x(3);

    system("PAUSE");

    return 0;
}

The result of this code execution is: X(int) constructor was called . But why the destructor message have not been printed?

As I understand, we create object x by calling constructor X(int) and in the end of the program this object have to be deleted, but it did not.

4

4 回答 4

3

由于它是在堆栈上分配的,因此应在此处调用 Destructor:

int main()
{
    X x(3);

    system("PAUSE");

    return 0;
} // X destructor (x go out of context)
于 2013-05-16T15:01:44.300 回答
2

析构函数在对象超出范围时运行。我猜你放system("pause")看它的信息。好吧,不,范围x还没有结束,它在return 0;.

从终端运行您的程序并亲自查看。

于 2013-05-16T15:00:47.910 回答
1

尝试这个 :

int main()
{
    {
       X x(3);
    } // Your x object is being destroyed here

    system("PAUSE");

    return 0;
}

它将为 X 创建一个本地范围,以便您看到 X 被销毁。

于 2013-05-16T15:04:16.403 回答
1

在对象超出范围之前不会调用析构函数,并且在您退出 main 之前不会发生这种情况

这就是没有弹出消息的原因:当对象消失时,控制台已经消失。

于 2013-05-16T15:00:38.890 回答