In
object-oriented programming
Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of pr ...
, a destructor (sometimes abbreviated dtor) is a
method
Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to:
*Scien ...
which is invoked mechanically just before the memory 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 ...
is released.
It can happen when its
lifetime is bound to
scope
Scope or scopes may refer to:
People with the surname
* Jamie Scope (born 1986), English footballer
* John T. Scopes (1900–1970), central figure in the Scopes Trial regarding the teaching of evolution
Arts, media, and entertainment
* Cinem ...
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 technologically accessible, economically feasible and culturally sustainable and help us to satisfy our needs and wants. Resources can broadly be classified upon their a ...
(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 re ...
s, 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).
With most kinds of
automatic garbage collection
In computer science, garbage collection (GC) is a form of automatic memory management. The ''garbage collector'' attempts to reclaim memory which was allocated by the program, but is no longer referenced; such memory is called ''garbage''. G ...
algorithms, the releasing of memory may happen a long time after the object becomes unreachable, making destructors (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 to ...
s in this case) unsuitable for most purposes. In such languages, the freeing of resources is done either through a lexical construct (such as try..finally, Python's "with" or Java's "try-with-resources"), which is the equivalent to RAII, or explicitly by calling a function (equivalent to explicit deletion); in particular, many object-oriented languages use
the Dispose pattern.
Destructor syntax
*
C++
C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
: destructors have the same name as the class with which they are associated, but with a
tilde
The tilde () or , is a grapheme with several uses. The name of the character came into English from Spanish, which in turn came from the Latin '' titulus'', meaning "title" or "superscription". Its primary use is as a diacritic (accent) in ...
(~) prefix.
*
D: destructors are declared with name
~this()
(whereas constructors are declared with
this()
).
*
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.
...
: destructors have the keyword
destructor
and can have user-defined names, but are mostly named
Destroy
.
*
Objective-C
Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTS ...
: the destructor method has the name
dealloc
.
*
Perl
Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
: the destructor method has the name
DESTROY
; in the
Moose object system extension, it is named
DEMOLISH
.
*
PHP
PHP is a general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by The PHP Group ...
: In PHP 5+, the destructor method has the name
__destruct
. There were no destructors in prior versions of PHP.
[Constructors and Destructors](_blank)
from PHP online documentation
*
Python
Python may refer to:
Snakes
* Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia
** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia
* Python (mythology), a mythical serpent
Computing
* Python (pro ...
: there are
__del__
methods called destructors by the Python 2 language guide, but they are actually
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 to ...
s as acknowledged 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 ...
: the destructor method for rust has the name
drop
*
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
* SWIFT, ...
: the destructor method has the name
deinit
.
In C++
The destructor has the same name as the class, but with a
tilde
The tilde () or , is a grapheme with several uses. The name of the character came into English from Spanish, which in turn came from the Latin '' titulus'', 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
__NOTOC__
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 b ...
, 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
In computer science, a smart pointer is an abstract data type that simulates a pointer while providing added features, such as automatic memory management or bounds checking. Such features are intended to reduce bugs caused by the misuse of poin ...
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 type
Scalar processors are a class of computer processors that process only one data item at a time. Typical data items include integers and floating point numbers.
Classification
A scalar processor is classified as a single instruction, single data ...
s 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
#include
#include
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
Scott Douglas Meyers (born April 9, 1959) is an American author and software consultant, specializing in the C++ computer programming language. He is known for his ''Effective C++'' book series. During his career, he was a frequent speaker at con ...
' 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 an optimizing compiler produced by the GNU Project supporting various programming languages, hardware architectures and operating systems. The Free Software Foundation (FSF) distributes GCC as free software ...
'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.
Xojo
Destructors in
Xojo
The Xojo programming environment and programming language is developed and commercially marketed by Xojo, Inc. of Austin, Texas for software development targeting macOS, Microsoft Windows, Linux, iOS, the Web and Raspberry Pi. Xojo uses a propri ...
(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
In computer programming and software design, code refactoring is the process of restructuring existing computer code—changing the '' factoring''—without changing its external behavior. Refactoring is intended to improve the design, structure ...
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 to ...
*
Constructor (computer science)
In class-based, object-oriented programming, a constructor (abbreviation: ctor) is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required ...
*
Object lifetime
In object-oriented programming (OOP), the object lifetime (or life cycle) of an object is the time between an object's creation and its destruction. Rules for object lifetime vary significantly between languages, in some cases between implementa ...
*
Resource Acquisition Is Initialization
References
{{Reflist
Method (computer programming)
C++