源码
// 05Destructor.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "iostream.h"
class Test
{
int i;
int *p;
public:
Test(int ai)
{
i = ai;
}
Test(int ai,int value)
{
i = ai;
p = new int(value);
}
~Test()
{
delete p;
}
};
//思考1:本例有什么错误?
//思考2:析构函数中应该释放哪些内存,如果构造中没有new,是不是就不需要析构函数了?
int main(int argc, char* argv[])
{
printf("Hello World!\n");
return 0;
}
思考1:本例有什么错误?
如果使用第一种构造方式,p为野指针,析构时delete p会报错。
思考2:析构函数中应该释放哪些内存,如果构造中没有new,是不是就不需要析构函数了?
应该释放通过new或malloc申请的内存。不是。