我正在研究C++
概念。我对构造函数和析构函数的概念感到困惑。析构函数将在程序退出时由编译器隐式调用。但是在我的程序中,只调用了构造函数。
#include <iostream>
using namespace std;
class A
{
int i;
public:
A()
{
cout<<"Constructor call"<<endl;
}
~A()
{
cout<<"Destructtor call"<<endl;
}
};
int main()
{
A *a = new A();
}
输出:
Constructor call
所以,我有一个问题:为什么编译器在退出程序时不隐式调用析构函数?
最佳答案
Why destructor not call implicit by the compiler upon exit program?
因为动态分配的对象不会自动销毁。这就是指定语言的方式。跟踪动态对象的销毁需要运行时/内存开销。
解决方案:不要泄漏动态分配的对象。
关于c++ - 为什么不在 C++ 中调用析构函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41870883/