“析构函数”是构造函数的反向函数。在销毁(释放)对象时将调用它们。通过在类名前面放置一个波形符 (~) 将函数指定为类的析构函数。例如,声明 String 类的析构函数:~String()。
在 /clr 编译中,析构函数在释放托管和非托管资源方面发挥了特殊作用。
析构函数通常用于在不再需要某个对象时“清理”此对象。请考虑 String 类的以下声明:
// spec1_destructors.cpp
#include
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() {
/