Destructor (computer science)
From Wikipedia, the free encyclopedia
In object-oriented programming, a destructor (sometimes shortened to dtor) is a method which is automatically invoked when the object is destroyed. Its main purpose is to clean up and to free the resources which were acquired by the object along its life cycle and unlink it from other objects or resources invalidating any references in the process. The use of destructors is key to the concept of RAII.
In a language with an automatic garbage collection mechanism, it is impossible to deterministically ensure the invocation of a destructor, and hence these languages are unsuitable for RAII. In such languages, unlinking an object from existing resources should be done by an explicit call of appropriate function (usually called Dispose
). This method is also recommended for freeing resources rather than using Finalizers for that.
Contents |
[edit] Virtual destructor
A virtual destructor is a destructor that can be overridden by subclasses. In C++, use of virtual destructors in inheritance hierarchies facilitates proper clean-up of objects, preventing resource leaks and heap corruption.
[edit] Examples
[edit] C++
In C++, the destructor function is the same name as the class, but with a tilde (~) in front of it. If the object was created locally, its destructor is automatically called, and if the object was created with the new
keyword, then its destructor is called when the pointer that points to the object is delete[]
'd. This particular class holds a_pointer to a list of character strings. A destructor is required when dynamically created data elements were used, files were opened, locks have to be unlocked or a copy constructor was used.
#include <string> class myclass { public: std::string* [] a_pointer; void newstring(void) { a_pointer[current] = new std::string(); current++; } ~myclass() // THIS IS THE DESTRUCTOR METHOD { int n = 0; while (n <= current) { delete a_pointer[n++]; } } private: int current; };
[edit] REALbasic
Destructors in REALbasic can be in one of two forms. Each form uses a regular method declaration with a special name (with no parameters and no return value). The older form uses the same name as the Class itself with a ~ (tilde) prefix. The newer form uses the name "Destructor." The newer form is the preferred one because it makes refactoring the class easier.
Class Foobar // Old form Sub ~Foobar() End Sub // New form Sub Destructor() End Sub End Class
[edit] See also
[edit] References
- Bjarne Stroustrup: The C++ Programming Language, Addison-Wesley, ISBN 0-201-70073-5