当前位置:网站首页>成员函数之析构函数
成员函数之析构函数
2022-07-13 19:21:00 【幻荼】
定义:
析构函数:与构造函数功能相反,析构函数不是完成对象的销毁,局部对象销毁工作是由编译器完成的。而对象在销毁时会自动调用析构函数,完成类的一些资源清理工作
特征:
1. 析构函数名是在类名前加上字符 ~。
2. 无参数无返回值。
3. 一个类有且只有一个析构函数。若未显式定义,系统会自动生成默认的析构函数。
4. 对象生命周期结束时,C++编译系统系统自动调用析构函数
举一个例子,大家来看下面的代码
typedef int DataType;
class SeqList
{
public:
SeqList(int capacity = 10)
{
_pData = (DataType*)malloc(capacity * sizeof(DataType));
assert(_pData);
_size = 0;
_capacity = capacity;
}
private:
int* _pData;
size_t _size;
size_t _capacity;
};我们都知道一般malloc了空间之后,我们都需要用free来释放空间。
而在实际操作当中,我们有时候会忽略free,而直接运行代码。
所以为了方便我们使用,这里的析构函数,相当于程序自动帮你补了一个free出来。
具体代码:
typedef int DataType;
class SeqList
{
public:
SeqList(int capacity = 10)
{
_pData = (DataType*)malloc(capacity * sizeof(DataType));
assert(_pData);
_size = 0;
_capacity = capacity;
}
~SeqList()
{
if (_pData)
{
free(_pData); // 释放堆上的空间
_pData = NULL; // 将指针置为空
_capacity = 0;
_size = 0;
}
}
private:
int* _pData;
size_t _size;
size_t _capacity;
};
边栏推荐
- Message Mechanism of dtcloud (1)
- PG operation and maintenance -- service start and stop
- jupyterlab 安装
- Shutter renderflex overflowed by pixels on the bottom keyboard pop-up warning exception
- Interprocess communication (very practical)
- HCIP第六天笔记
- ADB环境配置
- c语言 寄存器技巧 (struct 和 union)
- Lesson 3: stock trading III
- X书关键词搜索
猜你喜欢
随机推荐
【IDEA】check out master invalid path 问题
ODOO form视图详解(一)
Hcip day 5 notes
[go] II. Introduction to restful API, API process and code structure
jsp学习笔记
模拟实现库函数strcpy,对strcpy的进一步理解(深刻理解重叠问题,防止内存与源重叠)
Interprocess communication (very practical)
scipy.stats.chi2
人工智能与 RPA 技术应用(一)-RPA弘玑产品介绍、设计器界面功能讲解
Common mailbox access protocols
GPU资源池的虚拟化路径
Anonymous pipeline principle and detailed explanation (very practical)
LeetCode 1584. 连接所有点的最小费用
Judge whether two binary trees are isomorphic, and three implementation methods (recursion, queue, stack)
Is it safe to open an account for stock speculation through the online account manager?
05.01 字符串
Hj9 extract non duplicate integer hj09
Hcip second day notes
HCIP第五天实验
匿名管道原理及详解(非常实用)








