先看一个程序:
#include <iostream>
using namespace std;
class A
{
public:
A()
{
cout << "constructor" << endl;
}
~A()
{
cout << "destructor" << endl; // 没有被调用
}
};
int main()
{
void *p = new A; // void * 形式的指针
delete p;
return 0;
}
可以看到, 析构函数没有被调用, 如果析构函数中有非常重要的操作, 那么上述程序就有可能产生错误, 常见的就是内存泄露。