“析构函数”是构造函数的反向函数。在销毁(释放)对象时将调用它们。通过在类名前面放置一个波形符 (~) 将函数指定为类的析构函数。例如,声明 String 类的析构函数:~String()。
在 /clr 编译中,析构函数在释放托管和非托管资源方面发挥了特殊作用。
析构函数通常用于在不再需要某个对象时“清理”此对象。请考虑 String 类的以下声明:
// spec1_destructors.cpp
#include <string.h>
class String {
public:
String( char *ch ); // Declare constructor
~String(); // and destructor.
private:
char *_text;
size_t sizeOfText;
};
// Define the constructor.
String::String( char *ch ) {
sizeOfText = strlen( ch ) + 1;
// Dynamically allocate the correct amount of memory.
_text = new char[ sizeOfText ];
// If the allocation succeeds, copy the initialization string.
if( _text )
strcpy_s( _text, sizeOfText, ch );
}
// Define the destructor.
String::~String() {
// Deallocate the memory that was previously reserved
// for this string.
if (_text)
delete[] _text;
}
int main() {
String str("The piper in the glen...");
}
在前面的示例中,析构函数 String::~String 使用 delete 运算符来动态释放为文本存储分配的空间。
声明析构函数
析构函数是具有与类相同的名称但前面是波形符 (~) 的函数
该语法的第一种形式用于在类声明中声明或定义的析构函数;第二种形式用于在类声明的外部定义的析构函数。
多个规则管理析构函数的声明。析构函数:
- 不接受参数。
- 无法指定任何返回类型(包括 void)。
- 无法使用 return 语句返回值。
- 无法声明为 const、volatile 或 static。但是,可以为声明为 const、volatile 或 static 的对象的析构调用它们。
-
可以声明为 virtual。通过使用虚拟析构函数,无需知道对象的类型即可销毁对象 - 使用虚函数机制调用该对象的正确析构函数。请注意,析构函数也可以声明为抽象类的纯虚函数。
使用构造函数
当下列事件之一发生时,将调用析构函数:
使用 delete 运算符显式解除分配了使用 new 运算符分配的对象。使用 delete 运算符解除分配对象时,将为“大多数派生对象”或为属于完整对象,但不是表示基类的子对象的对象释放内存。此“大多数派生对象”解除分配一定仅对虚拟析构函数有效。在类型信息与实际对象的基础类型不匹配的多重继承情况下,取消分配可能失败。










