Destructor (computer science)
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 includes closing database connections, releasing network resources, relinquishing resource locks, etc.) 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 Resource Acquisition Is Initialization
(RAII).
In binary
programs
compiled with the GNU C Compiler
, special table sections called .dtors are made for destructors. This table contains an array of addresses to the relevant functions that are called when the main function exits.
A function can be declared as a destructor function by definining the destructor attribute __attribute__ ((destructor)) for a static function
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
s for that.
(~) in front of it. If the object was created as an automatic variable, its destructor is automatically called when it goes out of scope
. If the object was created with a new expression, then its destructor is called when the 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.
Objects which cannot be safely copied should be disabled from such semantics by declaring their corresponding functions within a non-public encapsulation level (in the above example, "private"). A detailed description of this technique can be found in Scott Meyers
' popular book, Effective C++ (Item 6: "Explicitly disallow the use of compiler-generated functions you do not want.").
's C
compiler comes with 2 extensions that allow to implement destructors:
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
Object-oriented programming
Object-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...
, a destructor (sometimes shortened to dtor) is a method
Method (computer science)
In object-oriented programming, a method is a subroutine associated with a class. Methods define the behavior to be exhibited by instances of the associated class at program run time...
which is automatically invoked when the object
Object (computer science)
In computer science, an object is any entity that can be manipulated by the commands of a programming language, such as a value, variable, function, or data structure...
is destroyed. Its main purpose is to clean up and to free the resources
Resource (computer science)
A resource, or system resource, is any physical or virtual component of limited availability within a computer system. Every device connected to a computer system is a resource. Every internal system component is a resource...
(which includes closing database connections, releasing network resources, relinquishing resource locks, etc.) 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 Resource Acquisition Is Initialization
Resource Acquisition Is Initialization
Resource Acquisition Is Initialization is a programming idiom used in several object-oriented languages like C++, D and Ada. The technique was invented by Bjarne Stroustrup to deal with resource deallocation in C++...
(RAII).
In binary
Binary file
A binary file is a computer file which may contain any type of data, encoded in binary form for computer storage and processing purposes; for example, computer document files containing formatted text...
programs
Computer program
A computer program is a sequence of instructions written to perform a specified task with a computer. A computer requires programs to function, typically executing the program's instructions in a central processor. The program has an executable form that the computer can use directly to execute...
compiled with the GNU C Compiler
GNU Compiler Collection
The GNU Compiler Collection is a compiler system produced by the GNU Project supporting various programming languages. GCC is a key component of the GNU toolchain...
, special table sections called .dtors are made for destructors. This table contains an array of addresses to the relevant functions that are called when the main function exits.
A function can be declared as a destructor function by definining the destructor attribute __attribute__ ((destructor)) for a static function
In a language with an automatic garbage collection
Garbage collection (computer science)
In computer science, garbage collection is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory occupied by objects that are no longer in use by the program...
mechanism, it would be difficult to deterministically ensure the invocation of a destructor, and hence these languages are generally considered unsuitable for RAII
Resource Acquisition Is Initialization
Resource Acquisition Is Initialization is a programming idiom used in several object-oriented languages like C++, D and Ada. The technique was invented by Bjarne Stroustrup to deal with resource deallocation in C++...
. 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 finalizerFinalizer
In object-oriented programming languages that use garbage collection, a finalizer is a special method that is executed when an object is garbage collected. It is similar in function to a destructor...
s for that.
Destructor syntax
- C++ has the naming convention in which destructors have the same name as the class of which they are associated with, but prefixed with a tildeTildeThe tilde is a grapheme with several uses. The name of the character comes from Portuguese and Spanish, from the Latin titulus meaning "title" or "superscription", though the term "tilde" has evolved and now has a different meaning in linguistics....
(~). - In Object PascalObject PascalObject Pascal refers to a branch of object-oriented derivatives of Pascal, mostly known as the primary programming language of Embarcadero Delphi.-Early history at Apple:...
, destructors have the keyword "destructor
" and can have user-defined names (but are mostly called "Destroy"). - In PerlPerlPerl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...
, the destructor method is named DESTROY. - In Moose object system for Perl, the destructor method is named DEMOLISH.
- In Objective-CObjective-CObjective-C is a reflective, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.Today, it is used primarily on Apple's Mac OS X and iOS: two environments derived from the OpenStep standard, though not compliant with it...
, the destructor method is named "dealloc
". - In PHP 5, the destructor method is named "
__destruct
". There were no destructors in previous versions of PHP.
In C++
The destructor has the same name as the class, but with a tildeTilde
The tilde is a grapheme with several uses. The name of the character comes from Portuguese and Spanish, from the Latin titulus meaning "title" or "superscription", though the term "tilde" has evolved and now has a different meaning in linguistics....
(~) in front of it. If the object was created as an automatic variable, its destructor is automatically called when it goes out of scope
Scope (programming)
In computer programming, scope is an enclosing context where values and expressions are associated. Various programming languages have various types of scopes. The type of scope determines what kind of entities it can contain and how it affects them—or semantics...
. If the object was created with a new expression, then its destructor is called when the delete operator is applied to a pointer to the object. Usually that operation occurs within another destructor, typically the destructor of a smart pointer
Smart pointer
In computer science, a smart pointer is an abstract data type that simulates a pointer while providing additional features, such as automatic garbage collection or bounds checking. These additional features are intended to reduce bugs caused by the misuse of pointers while retaining efficiency...
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.
Example
Objects which cannot be safely copied should be disabled from such semantics by declaring their corresponding functions within a non-public encapsulation level (in the above example, "private"). A detailed description of this technique can be found in Scott Meyers
Scott Meyers
Scott Douglas Meyers is an American author and software consultant, specializing in the C++ computer programming language. He is known for his Effective C++ book series. He is a frequent speaker at conferences and trade shows. He holds a Ph.D. in computer science from Brown University and M.S...
' popular book, Effective C++ (Item 6: "Explicitly disallow the use of compiler-generated functions you do not want.").
In C with GCC extensions
The GNU Compiler CollectionGNU Compiler Collection
The GNU Compiler Collection is a compiler system produced by the GNU Project supporting various programming languages. GCC is a key component of the GNU toolchain...
's C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
compiler comes with 2 extensions that allow to implement destructors:
- the "destructor" function attribute allows to define global prioritized destructor functions: when main returns, these functions are called in priority order before the process terminates;
- the "cleanup" variable attribute allows to attach a destructor function to a variable: the function is called when the variable goes out of scope.
REALbasic
Destructors in REALbasicREALbasic
Realbasic is the object-oriented dialect of the BASIC programming language used in Real Studio, a programming environment, developed and commercially marketed by Real Software, Inc of Austin, Texas for Mac OS X, Microsoft Windows, 32-bit x86 Linux and the web.- Language features :RB is a strongly...
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
Refactoring
Code refactoring is "disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior", undertaken in order to improve some of the nonfunctional attributes of the software....
the class easier.
Class Foobar
// Old form
Sub ~Foobar
End Sub
// New form
Sub Destructor
End Sub
End Class
See also
- FinalizerFinalizerIn object-oriented programming languages that use garbage collection, a finalizer is a special method that is executed when an object is garbage collected. It is similar in function to a destructor...
- ConstructorConstructor (computer science)In object-oriented programming, a constructor in a class is a special type of subroutine called at the creation of an object. It prepares the new object for use, often accepting parameters which the constructor uses to set any member variables required when the object is first created...
- Object lifetimeObject lifetimeIn computer science, the object lifetime of an object in object-oriented programming is the time between an object's creation till the object is no longer used, and is destructed or freed.In object-oriented programming , the meaning of creating objects is far more subtle than simple...
- Resource Acquisition Is InitializationResource Acquisition Is InitializationResource Acquisition Is Initialization is a programming idiom used in several object-oriented languages like C++, D and Ada. The technique was invented by Bjarne Stroustrup to deal with resource deallocation in C++...