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