In
object-oriented programming
Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impl ...
, a destructor (sometimes abbreviated dtor) is a
method
Method (, methodos, from μετά/meta "in pursuit or quest of" + ὁδός/hodos "a method, system; a way or manner" of doing, saying, etc.), literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In re ...
which is invoked mechanically just before the
memory
Memory is the faculty of the mind by which data or information is encoded, stored, and retrieved when needed. It is the retention of information over time for the purpose of influencing future action. If past events could not be remembe ...
of the
object
Object may refer to:
General meanings
* Object (philosophy), a thing, being, or concept
** Object (abstract), an object which does not exist at any particular time or place
** Physical object, an identifiable collection of matter
* Goal, an a ...
is released.
It can happen either 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
''Resource'' refers to all the materials available in our environment which are Technology, technologically accessible, Economics, economically feasible and Culture, culturally Sustainability, sustainable and help us to satisfy our needs and want ...
(memory allocations, open files or sockets,
database connection A database connection is a facility in computer science that allows client software to talk to database server software, whether on the same machine or not. A connection is required to send commands and receive answers, usually in the form of a ...
s,
resource locks, etc.) which were acquired by the object during its life and/or deregister from other entities which may keep
references
A reference is a relationship between Object (philosophy), objects in which one object designates, or acts as a means by which to connect to or link to, another object. The first object in this relation is said to ''refer to'' the second object. ...
to it. Destructors are necessary in
resource acquisition is initialization (RAII).
With most kinds of
automatic garbage collection algorithms, the releasing of memory may happen a long time after the object becomes unreachable, making destructors unsuitable for time-critical purposes. In these languages, the freeing of resources is done through an lexical construct (such as try-finally, Python's
with
, or Java's "try-with-resources"), or by explicitly calling a function (equivalent to explicit deletion); in particular, many object-oriented languages use the
dispose pattern.
Syntax
*
C++: destructors have the same name as the class with which they are associated, but with a
tilde
The tilde (, also ) is a grapheme or with a number of uses. The name of the character came into English from Spanish , which in turn came from the Latin , meaning 'title' or 'superscription'. Its primary use is as a diacritic (accent) in ...
prefix (for example, a class
X
with a constructor
X()
has a destructor
~X()
).
*
C#: same syntax as C++. Historically called destructors, now called
finalizer
In computer science, a finalizer or finalize method is a special method that performs finalization, generally some form of cleanup. A finalizer is executed during object destruction, prior to the object being deallocated, and is complementary ...
s due to confusion.
*
D: declared as
~this()
(whereas constructors are declared as
this()
).
*
Java
Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
: provided by 2 interfaces,
Closeable
and
AutoCloseable
. Closeable is deprecated . In Java 9+, destructors are replaced by ''cleaners''.
*
Object Pascal
Object Pascal is an extension to the programming language Pascal (programming language), Pascal that provides object-oriented programming (OOP) features such as Class (computer programming), classes and Method (computer programming), methods.
T ...
: destructor methods have the keyword
destructor
and can be any name, but convention is
Destroy
.
*
Objective-C
Objective-C is a high-level general-purpose, object-oriented programming language that adds Smalltalk-style message passing (messaging) to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was ...
: destructor method is named
dealloc
.
*
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language".
Perl was developed ...
: destructor method is named
DESTROY
; in the
Moose object system extension, it is named
DEMOLISH
.
*
PHP: In PHP 5+, destructor method is named
__destruct
. There were no destructors in prior versions of PHP.
[Constructors and Destructors](_blank)
from PHP online documentation
*
Python: destructor method is named
__del__
. Called destructors in Python 2, now called
finalizer
In computer science, a finalizer or finalize method is a special method that performs finalization, generally some form of cleanup. A finalizer is executed during object destruction, prior to the object being deallocated, and is complementary ...
s in Python 3.
*
Rust
Rust is an iron oxide, a usually reddish-brown oxide formed by the reaction of iron and oxygen in the catalytic presence of water or air moisture. Rust consists of hydrous iron(III) oxides (Fe2O3·nH2O) and iron(III) oxide-hydroxide (FeO(OH) ...
: destructor method is named
drop
and is provided by the
Drop
trait.
*
Swift
Swift or SWIFT most commonly refers to:
* SWIFT, an international organization facilitating transactions between banks
** SWIFT code
* Swift (programming language)
* Swift (bird), a family of birds
It may also refer to:
Organizations
* SWIF ...
: destructor method is named
deinit
.
In C++
The destructor has the same name as the class, but with a
tilde
The tilde (, also ) is a grapheme or with a number of uses. The name of the character came into English from Spanish , which in turn came from the Latin , meaning 'title' or 'superscription'. Its primary use is as a diacritic (accent) in ...
(~) before it.
For example, a class called foo will have the destructor . Additionally, destructors have neither parameters nor return types.
As stated above, a destructor for an object is called whenever the object's lifetime ends.
If the object was created as an
automatic variable
In computer programming, an automatic variable is a local variable which is allocated and deallocated automatically when program flow enters and leaves the variable's scope. The scope is the lexical context, particularly the function or block in ...
, 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
statement (dynamically on the
heap), then its destructor is called when the
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.
Non-class
scalar types have what's called a which can be accessed by using
typedef
or template arguments. This construct makes it possible to write code without having to know if a destructor exists for a given type.
int f()
In older versions of the standard, pseudo-destructors were specified to have no effect, however that was changed in a defect report to make them end the lifetime of the object they are called on.
Example
import std;
class Foo ;
int main()
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.").
In C with GCC extensions
The
GNU Compiler Collection
The GNU Compiler Collection (GCC) is a collection of compilers from the GNU Project that support various programming languages, Computer architecture, hardware architectures, and operating systems. The Free Software Foundation (FSF) distributes ...
's
C compiler comes with 2 extensions that allow implementing destructors:
* The
destructor
function attribute 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''.
* The
''cleanup'' variable attribute allows attaching a destructor function to a variable: the function is called when the variable goes out of scope.
In Java
Java provides 2 interfaces that implement destructors,
Closeable
and
AutoCloseable
. A class that implements AutoCloseable is able to be used in a "try-with-resources" block, available since Java 7.
public final class Destructors implements AutoCloseable
public final class Test Prior to Java 7, a "try-finally" block was used.
public final class Destructors
public final class Test
In 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
*
Finalizer
In computer science, a finalizer or finalize method is a special method that performs finalization, generally some form of cleanup. A finalizer is executed during object destruction, prior to the object being deallocated, and is complementary ...
*
Constructor (computer science)
In class-based, object-oriented programming, a constructor (abbreviation: ctor) is a special type of function called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required ...
*
Object lifetime
Object may refer to:
General meanings
* Object (philosophy), a thing, being, or concept
** Object (abstract), an object which does not exist at any particular time or place
** Physical object, an identifiable collection of matter
* Goal, an ...
*
Resource Acquisition Is Initialization
*
Rule of three (C++ programming)
References
{{Reflist
Method (computer programming)
C++