相关知识:
- 析构函数(
destructor
)是成员函数的一种,它的名字与类名相同,但前面要加~
,没有参数和返回值。 - 析构函数有助于在跳出程序(比如关闭文件、释放内存等)前释放资源。
- 一个类有且仅有一个析构函数。如果定义类时没写析构函数,则编译器生成默认析构函数。如果定义了析构函数,则编译器不生成默认析构函数。
- 类的析构函数是类的一种特殊的成员函数,它会在每次删除所创建的对象时执行。
- 当对象脱离其作用域时(例如对象所在的函数已调用完毕),系统会自动执行析构函数。析构函数往往用来做“清理善后”的工作(例如在建立对象时用
new
开辟了一段内存空间,则在该对象消亡前应在析构函数中用delete
释放这段存储空间)。 - 析构函数在对象消亡时即自动被调用。可以定义析构函数在对象消亡前做善后工作。
- 有了析构函数,只要在析构函数中调用
delete
语句,就能确保对象运行中用new
运算符分配的空间在对象消亡时被释放。 - 与复制构造函数不同,编译器总是会为类生成一个析构函数,称为合成析构函数(
synthesized destructor
)合成析构函数按对象创建时的逆序撤销每个非静态成员,即它是按成员在类中声明次序的逆序撤销成员的。对于类类型的每个成员,合成析构函数调用该成员的析构函数来撤销对象。需要注意,合成析构函数并不删除指针成员所指向的对象,它需要程序员显式编写析构函数去处理。
何时调用析构函数:
(1)对象在程序运行超出其作用域时自动撤销,撤销时自动调用该对象的析构函数。如函数中的非静态局部对象。
(2)如果用new运算动态地建立了一个对象,那么用delete
运算释放该对象时,调用该对象的析构函数。
(3)许多类不需要显式地编写析构函数,尤其是具有构造函数的类不一定需要定义自己的析构函数。析构函数通常用于释放在构造函数或在对象生命期内获取的资源(如动态分配的内存)。
(4)但是,析构函数的作用并不仅限于释放资源方面,它可以包含任意操作,用来执行“对象即将被撤销之前程序员所期待的任何操作。
(5)如果类需要析构函数,则该类几乎必然需要定义自己的复制构造函数和赋值运算符重载,这个规则称为析构函数三法则(rule of three
)。
调用次序:
- 在使用构造函数和析构函数时,需要特别注意对它们的调用时间和调用次序。
- 构造函数和析构函数的调用很像一个栈的先进后出,调用析构函数的次序正好与调用构造函数的次序相反。最先被调用的构造函数,其对应的(同一对象中的)析构函数最后被调用,而最后被调用的构造函数,其对应的析构函数最先被调用。
代码涉及的内容:
- 构造函数:获取资源(出生)
- 析构函数:释放资源(死掉)
- 合成的析构函数
- 三法则(rule of three)
1 |
|