Freigeben über


Destructors (C++)

"Destructor" functions are the inverse of constructor functions. They are called when objects are destroyed (deallocated). Designate a function as a class's destructor by preceding the class name with a tilde (~). For example, the destructor for class String is declared: ~String().

In a /clr compilation, the destructor has a special role in releasing managed and unmanaged resources. See Destructors and Finalizers in Visual C++ for more information.

Example

The destructor is commonly used to "clean up" when an object is no longer necessary. Consider the following declaration of a String class:

// 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...");
}

In the preceding example, the destructor String::~String uses the delete operator to deallocate the space dynamically allocated for text storage.

See Also

Concepts

Special Member Functions