菜鸟笔记
提升您的技术认知

析构函数详解

析构函数详解

析构函数的概念
  • 前面通过构造函数的学习,我们知道一个对象是怎么来的,那一个对象又是怎么没呢的?
  • 析构函数:与构造函数功能相反,析构函数是完成对象的销毁,局部对象销毁工作是由编译器完成的。而对象在销毁时会自动调用析构函数,完成类的一些资源清理工作。
  • 析构函数用来完成对象资源清理的工作
析构函数的特性
  • 析构函数名是在类名前加上字符 ~。
  • 无参数无返回值。
  • 一个类有且只有一个析构函数。若用户没有显式定义,系统会自动生成默认的析构函数。
  • 当对象生命周期结束时,C++编译系统系统会自动调用析构函数
  • 下面是通过C++的类,来封装顺序表
#include<iostream>
#include<assert.h>
using namespace std;

class SeqList
{
  
public:
	SeqList(int capacity = 10)
	{
  
		array = (int*)malloc(sizeof(int) * capacity);
		assert(array);
		_capacity = capacity;
		_size = 0;
	}
private:
	int* array;
	int _size;
	int _capacity;
};
void TestSeqList()
{
  
	SeqList s;
}
int main()
{
  
	SeqList s(100);

	return 0;
}
但是上面的代码存在有很大的问题,就是代码中所创建的变量并没有被销毁和释放,用析构函数来清理资源
  • 在这种情况下,我们需要使用析构函数来完成对象资源的销毁工作。
#include<iostream>
#include<assert.h>
using namespace std;

class SeqList
{
  
public:
	SeqList(int capacity = 10)
	{
  
		cout << "SeqList(int):" << this << endl;
		array = (int*)malloc(sizeof(int) * capacity);
		assert(array);
		_capacity = capacity;
		_size = 0;
	}

	//析构函数
	~SeqList()
	{
  
		if (array)
		{
  
			free(array);
			_capacity = 0;
			_size = 0;
		}
		cout << "~SeqList():" << this << endl;
	}
private:
	int* array;
	int _size;
	int _capacity;
};
void TestSeqList()
{
  
	SeqList s;
}
int main()
{
  
	SeqList s(100);

	return 0;
}
析构函数不能重载
  • 析构函数没有参数,所以析构函数无法重载,都没有参数,怎么重载
关于编译器自动生成的析构函数,是否会完成一些事情呢?下面的程序我们会看到,编译器生成的默认析构函数,对会自定类型成员调用它的析构函数
#include<iostream>
#include<string.h>
using namespace std;
class String
{
  
public:
	String(const char* str = "jack")
	{
  
		_str = (char*)malloc(strlen(str) + 1);
		strcpy(_str, str);
	}
	~String()
	{
  
		cout << "~String()" << endl;
		free(_str);
	}
private:
	char* _str;
};
class Person
{
  
private:
	String _name;
	int _age;
};
int main()
{
  
	Person p;
	return 0;
}
编译器也会生成默认的析构函数