C++ 05 —— 析构函数

来源:互联网 发布:linux google输入法 编辑:程序博客网 时间:2024/06/08 02:54

源码

// 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申请的内存。不是。

原创粉丝点击