输出错误

哈西特

我正在使用Dev C ++编译器。我有这个代码:

#include <iostream>
using std::cout;
class Test
{
    public:
        Test();
        ~Test();
};
Test::Test()
{
        cout << "Constructor is executed\n";
}
Test::~Test()
{
        cout << "Destructor is executed\n";
}
int main()
{
        new Test();
        return 0;
}

输出

    Constructor is executed

在此代码中,为什么不自动调用Destructor。

但是当我尝试这段代码时:

#include <iostream>
using std::cout;
class Test
{
    public:
        Test();
        ~Test();
};
Test::Test()
{
        cout << "Constructor is executed\n";
}
Test::~Test()
{
        cout << "Destructor is executed\n";
}
int main()
{
        delete new Test();
        return 0;
}

输出

    Constructor is executed
    Destructor is executed

这些产出差异的原因是什么?

加布里埃尔

这是因为delete使用new调用刚创建的对象的析构函数。

因此在这种情况下,没有delete =没有析构函数调用。

看起来您是C ++的新手,因此对于您的信息,两个对象都在堆上创建。(将此用于将来的研究)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章