C++基础(十)C++的析构函数:对象消亡时动态释放内存

一、析构函数举例1

参考:http://c.biancheng.net/view/152.html

         一个类有且仅有一个析构函数。如果定义类时没写析构函数,则编译器生成默认析构函数。如果定义了析构函数,则编译器不生成默认析构函数。
        析构函数在对象消亡时即自动被调用。可以定义析构函数在对象消亡前做善后工作。例如,对象如果在生存期间用 new 运算符动态分配了内存,则在各处写 delete 语句以确保程序的每条执行路径都能释放这片内存是比较麻烦的事情。有了析构函数,只要在析构函数中调用 delete 语句,就能确保对象运行中用 new 运算符分配的空间在对象消亡时被释放。例如下面的程序:

#include<iostream>
using namespace std;
class CDemo {
public:
    ~CDemo() {  //析构函数
        cout << "Destructor called"<<endl;
    }
};
int main() {
    CDemo array[2];  //构造函数调用2次
    CDemo* pTest = new CDemo;  //构造函数调用
    delete pTest;  //析构函数调用
    cout << "-----------------------" << endl;
    pTest = new CDemo[2];  //构造函数调用2次
    delete[] pTest;  //析构函数调用2次
    cout << "Main ends." << endl;
    return 0;
}

程序的输出结果是:
Destructor called
-----------------------
Destructor called
Destructor called
Main ends.
Destructor called
Destructor called

        第一次析构函数调用发生在第 13 行,delete 语句使得第 12 行动态分配的 CDemo 对象消亡。
        接下来的两次析构函数调用发生在第 16 行,delete 语句释放了第 15 行动态分配的数组,那个数组中有两个 CDemo 对象消亡。最后两次析构函数调用发生在 main 函数结束时,因第 11 行的局部数组变量 array 中的两个元素消亡而引发。

二、析构函数举例2

参考:

https://blog.csdn.net/qq_15267341/article/details/78997736

#include "stdafx.h"
#include <iostream>

using namespace std;
class haitao{
private:
    int ageee;
public :
    int getAgee(){
        return ageee;
    }
    haitao(){
        cout << "无参构造函数被调用" << endl;
    }
    ~haitao(){
        cout << "析构函数被调用" << endl;
    }

};
void test(){
    haitao tt; //对象建立
    //方法结束时,由系统自动调用析构函数释放对象
}

int _tmain(int argc, _TCHAR* argv[])
{
    test();
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/xpj8888/article/details/85272696