デストラクター (C++)
"デストラクター" 関数は、コンストラクター関数の逆の操作を行います。 呼び出されるのは、オブジェクトが破棄 (割り当てを解放) されるときです。 関数をクラスのデストラクターとして指定するには、クラス名の前にティルダ (~) を付けます。 たとえば、クラス String のデストラクターを宣言するには、~String() とします。
/clr のコンパイルでは、マネージおよびアンマネージ リソースを解放する際に、デストラクターが特別な役割を果たします。 詳細については、「Visual C++ のデストラクター、およびファイナライザー」を参照してください。
使用例
デストラクターは、通常、オブジェクトが不要になったときに "クリーンアップ" を行うために使用されます。 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 演算子を使用して、テキストの保存のために動的に割り当てられた領域を解放します。