다음을 통해 공유


소멸자 (C++)

"소멸자" 함수는 생성자 함수의 역함수 값입니다. 그들은 개체 소멸 될 때 호출됩니다 (할당이 해제 될 때). 물결표 (~) 를 사용하여 클래스 이름 앞에 클래스의 소멸자 함수 지정. 예를 들어, 클래스 소멸자 String 선언: ~String().

/clr 컴파일에서, 소멸자는 관리를 해제 하고 관리 되지 않는 리소스에 특수 역할을 갖습니다. 자세한 내용은 소멸자 및 종료자에서를 참조하십시오.

예제

개체가 더 이상 필요 없을 때, 소멸자는 "정리" 하는 데 주로 사용 됩니다. 다음 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++)