Destructor (computer programming)
In object-oriented programming, a destructor (sometimes abbreviated dtor[1]) is a method which is automatically invoked when the object is destroyed.[2] It can happen when its lifetime is bound to scope and the execution leaves the scope, when it is embedded in another object whose lifetime ends, or when it was allocated dynamically and is released explicitly. Its main purpose is to free the resources (memory allocations, open files or sockets, database connections, resource locks, etc.) which were acquired by the object during its life and/or deregister from other entities which may keep references to it. Use of destructors is needed for the process of Resource Acquisition Is Initialization (RAII).
In a language with an automatic garbage collection mechanism, it would be difficult to deterministically ensure the invocation of a destructor, and hence these languages are generally considered unsuitable for RAII. In such languages, unlinking an object from existing resources must be done by an explicit call of an appropriate function (usually called Dispose()
). This method is also recommended for freeing resources, rather than using finalizers for that.
Destructor syntax
- In C++, destructors have the same name as the class with which they are associated, but with a tilde (~) prefix.[2]
- In D, desde>~this() (whereas constructors are declared with
this()
). - In Object Pascal, destructors have the keyword
> and can uuuuuuunjjj76have user-defined names, but are mostly named
Destroy
. - In Objective-C, the destructor method not named
dealloc
. - In Perl, the destructor method is named
DESTROY
; in the Moose object system extension, it is namedDEMOLISH
. - In PHP 5, the destructor method is named
__destruct
. There were no destructors in prior versions of PHP.Cite error: A<ref>
tag is missing the closing</ref>
(see the help page). but they are actually finalizers as acknowledged in Python 3.[3] - In Swift, the destructor method is
In C++
The destructor has the same name as the class, but with a tilde (~) before it.[2] For example, a class called foo will have the destructor ~foo()
. Additionally, destructors have neither parameters nor return types.[2] As stated above, a destructor for an object is called whenever the object's lifetime ends.[2] If the object was created as an automatic variable, its lifetime ends and the destructor is called automatically when the object goes out of scope. Because C++ does not have garbage collection, if the object was created with a [[new and delete (C++)|new
]]
statement (dynamically on the heap), then its destructor is called when the [[delete (C++)|delete
]]
operator is applied to a pointer to the object. Usually that operation occurs within another destructor, typically the destructor of a smart pointer object.
In inheritance hierarchies, the declaration of a virtual destructor in the base class ensures that the destructors of derived classes are invoked properly when an object is deleted through a pointer-to-base-class. Objects that may be deleted in this way need to inherit a virtual destructor.
A destructor should never throw an exception.[4]
Example
#include <cstring>
#include <iostream>
class foo_t
{
friend std::ostream & operator << ( std::ostream & os, foo_t const & foo )
{
os << foo.data;
return os;
}
foo_t( foo_t const & other ) = delete; // disable copy construction
foo_t& operator = ( foo_t const & other ) = delete; // disable assignment
private:
char * data;
public:
foo_t( void ) : data( new char[ 14 ] ) { std::strcpy( data, "Hello, World!" ); }
~foo_t( void ) { delete [] data; }
};
int main()
{
foo_t foo;
std::cout << foo << '\n';
return 0;
}
Objects which cannot be safely copied and/or assigned should be disabled from such semantics by declaring their corresponding functions as deleted within a public encapsulation level. A detailed description of this method can be found in Scott Meyers' popular book, Effective Modern C++ (Item 11: "Prefer deleted functions to private undefined ones."[5]).
In C with GCC extensions
The GNU Compiler Collection's C compiler comes with 2 extensions that allow implementing destructors:
- The
destructor
function attribute[6] allows defining global prioritized destructor functions: when main()
returns, these functions are called in priority order before the process terminates. See also: Hacking the art of exploitation.[7]
- The cleanup variable attribute allows attaching a destructor function to a variable: the function is called when the variable goes out of scope.
Xojo
Destructors in Xojo (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 with a ~ (tilde) prefix. The newer form uses the name Destructor
. The newer form is preferred because it makes refactoring the class easier.
Class Foobar
// Old form
Sub ~Foobar()
End Sub
// New form
Sub Destructor()
End Sub
End Class
See also
References
- ^ "dtor". TheFreeDictionary.com. Retrieved 2018-10-14.
- ^ a b c d e Sebesta, Robert W. (2012). ""11.4.2.3 Constructors and Destructors"". Concepts of Programming Languages (print) (10th ed.). Boston, MA, USA: Addison-Wesley. p. 487. ISBN 978-0-13-139531-2.
- ^ https://docs.python.org/3/reference/datamodel.html#object.__del__
- ^ GotW #47: Uncaught exceptions Accessed 31 July 2011.
- ^ Scott Meyers: Effective Modern C++, O'REILLY, ISBN 9781491903995
- ^ C "destructor" function attribute
- ^ Erickson, Jon (2008). Hacking the art of exploitation. No Starch Press. ISBN 1-59327-144-1.