デストラクター (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 の演算子を使用します。