In object-oriented programming, a destructor (sometimes abbreviated dtor) is a method which is invoked mechanically just before the memory of the object 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 (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. 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 a 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 prefix (for example, a class X with a constructor X() has a destructor ~X()). The destructor is called when an object's lifetime ends; if it is heap-allocated, it may be called manually by delete. C#: same syntax as C++ (~X()). Historically called destructors, now called finalizers due to confusion. Internally, it translates to a call to Finalize() inside System.Object. For freeing resources at the end of a using-with-resources block, the Dispose() method of System.IDisposable interface is used. D: declared as ~this() (whereas constructors are declared as this()). Until its removal in D 2.111.0, D had a delete keyword that called the destructor. Java: there are no destructors in Java like C++ or C#. java.lang.Object has a finalize() method, which may be called by the object collector (but is not guaranteed to be); overriding it has been deprecated since Java 9. java.lang.ref.Cleaner is recommended as a safer replacement to Object.finalize(). For freeing resources at the end of a try-with-resources block, the close() method of the java.lang.AutoCloseable interface is used. Object Pascal: destructor methods have the keyword destructor and can be any name, but convention is Destroy(). Objective-C: destructor method is named dealloc. Perl: 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. Python: destructor method is named __del__(). Called destructors in Python 2, now called finalizers in Python 3. The del keyword deletes a variable name/reference to an object, but does not directly call __del__(). Rust: destructor method is named drop() and is provided by the std::ops::Drop trait. Swift: destructor method is named deinit, but does not have parameters and is simply declared as a block (i.e. deinit { /* ... */ }). The keyword delete exists in the ECMAScript specification (and in dialects such as JavaScript and TypeScript), but unlike C++'s delete, delete in ECMAScript only removes a property from a class rather than deallocating and freeing the object.
Language details
C As C does not have objects, it has neither constructors nor destructors. However, they can be emulated using functions that allocate and destroy, to abstract away manual calls to malloc() and free().
GCC extensions The GNU Compiler Collection's C compiler comes with 2 extensions that allow implementing destructors:
The [[gnu::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 [[gnu::cleanup(func)]] variable attribute allows attaching a destructor function to a variable: the function is called when the variable goes out of scope.
C++ The destructor has the same name as the class, but with a tilde (~) before it. For example, a class called Foo will have the destructor ~Foo(). 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, 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 new (dynamically on the heap), 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; all destructors are implicitly marked noexcept, but can be allowed to throw if explicitly marked noexcept(false). If a class inherits from a class with a throwing destructor, or has a member variable whose destructor throws, then its destructor will not be implicitly noexcept. Non-class scalar types have what is called a pseudo-destructor 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.
… excerpt ends here. Continue reading the full article.
