c++ - 输出不正确

标签 c++ constructor destructor

我正在使用 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

在这段代码中,为什么没有自动调用析构函数。

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

#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

这些输出不同的原因是什么?

最佳答案

new 动态创建的对象永远不会自动销毁;它们只会被 delete 销毁。你的第一个例子没有这样做(所以对象被泄露),而你的第二个例子做到了。

如果想让它自动销毁,那么就给它自动存储时长:

int main()
{
    Test t;       // Created here, on declaration
    return 0;     // Destroyed here, when it goes out of scope
}

关于c++ - 输出不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27743021/

相关文章:

c++ - 任何对象的 OpenGL 光线转换

c# - 静态构造函数会导致性能开销?

javascript - 正则表达式构造函数和文字之间的反斜杠差异

c++ - 构造函数和析构函数 - C++

c++ - C++中的纯虚析构函数

c++ - 在 C++ 接口(interface)中声明模板函数?

c++ - 如何使用 Google 测试框架测试共享库

C++:具有用户定义类型的构造函数

C++:我可以在析构函数中安全地使用它吗?

c++ - 在 c++0x 中删除 nullptr 是否仍然安全?