共用方式為


解構函式 (C++)

「destructor」函式是反建構函式。 當物件終結時 (解除分配),他們會被呼叫。 藉由在類別名稱前面加上波狀符號 (~)將一個函式指定為類別的解構函式。 例如, String 類別的解構函式宣告: ~String()。

在 /clr 編譯,解構函式在釋放 Managed 和 Unmanaged 資源上有特殊效果。 如需詳細資訊,請參閱 解構函式和在 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 運算子解除動態配置給文字儲存的空間。

請參閱

參考

特殊成員函式 (C++)