my-server
← Wiki Redirected from Destructor (computer science)

Destructor (computer programming)

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 an lexical construct (such as try-finally, Python's <code>with</code>, 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 <code>X</code> with a constructor <code>X()</code> has a destructor <code>~X()</code>).
  • C#: same syntax as C++ (<code>~X()</code>). Historically called destructors, now called finalizers due to confusion.
  • D: declared as <code>~this()</code> (whereas constructors are declared as <code>this()</code>).
  • Java: there are no destructors in Java like C++ or C#, but there is a <code>close()</code> method provided by 2 interfaces, <code>Closeable</code> (deprecated) and <code>AutoCloseable</code>. In Java 9+, "destructors" are replaced by <code>Cleaner</code>. Java also used to have <code>Object.finalize()</code>, which was also deprecated.
  • Object Pascal: destructor methods have the keyword <code>destructor</code> and can be any name, but convention is <code>Destroy</code>.
  • Objective-C: destructor method is named <code>dealloc</code>.
  • Perl: destructor method is named <code>DESTROY</code>; in the Moose object system extension, it is named <code>DEMOLISH</code>.
  • PHP: In PHP 5+, destructor method is named <code>__destruct</code>. There were no destructors in prior versions of PHP.
  • Python: destructor method is named <code>__del__</code>. Called destructors in Python 2, now called finalizers in Python 3.
  • Rust: destructor method is named <code>drop</code> and is provided by the <code>Drop</code> trait.
  • Swift: destructor method is named <code>deinit</code>.

The keyword <code>delete</code> exists in JavaScript and TypeScript, but unlike in C++, <code>delete</code> in those language removes a property from a class.

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 <code>malloc()</code> and <code>free()</code>.

GCC extensions

The GNU Compiler Collection's C compiler comes with 2 extensions that allow implementing destructors:

  • The <code>destructor</code> function attribute allows defining global prioritized destructor functions: when <code>main()</code> 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.

C++

The destructor has the same name as the class, but with a tilde () before it. For example, a class called <code>Foo</code> 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, 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 <code>typedef</code> or template arguments. This construct makes it possible to write code without having to know if a destructor exists for a given type.

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.

In C++/CLI, which has both destructors and finalizers, a destructor is a method whose name is the class name with prefixed, as in <code>~Foo()</code> (as in C#), and a finalizer is a method whose name is the class name with prefixed, as in <code>!Foo()</code>.

Objects which cannot be safely copied and/or assigned should be disabled from such semantics by declaring their corresponding functions as deleted. 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."). If they are marked <code>delete</code>d, they should be <code>public</code> so that accidental uses do not warn that they are <code>private</code>, but explicitly <code>delete</code>d. Since C++26, it is possible to specify a reason for the deletion.

Example

By using smart pointers with the "Resource Acquisition is Initialization" (RAII) idiom, manual resource cleanup can be abstracted. Other languages like Java and C# include a <code>finally</code> block for cleanup, however C++ does not have the <code>finally</code> block and instead encourages using the RAII idiom.

C#

C# also has a "dispose" pattern in which the class must implement the interface <code>IDisposable</code>. C# supports try-with-resources blocks similar to Java, called using-with-resources. A class must implement <code>IDisposable</code> to be used in a using-with-resources block.

Destructors in C# are not manually called or called by a <code>delete</code> operator like in C++. They are only called by the garbage collector.

However, finalizers should only be used when absolutely necessary, such as handling unmanaged resources like pointers and native handles. This is because adding a finalizer moves the object to the finalization queue and requires at least two garbage collection cycles, which slows performance and increases memory pressure.

Java

In Java there are no true "destructors" like C++ and C#, but Java does provide 2 interfaces that implement a <code>close()</code> method, <code>java.lang.Closeable</code> (deprecated) and <code>java.lang.AutoCloseable</code>. A class that implements <code>AutoCloseable</code> is able to be used in a "<code>try</code>-with-resources" block, available since Java 7. These <code>clean()</code> methods do not deallocate memory, as memory is reclaimed through garbage collection.

Prior to Java 7, a "<code>try</code>-<code>finally</code>" block was used, where the <code>d.close()</code> call was put inside the <code>finally</code> block.

Historically, Java used <code>Object.finalize()</code> instead, however this has been deprecated. Java has a method called <code>System.gc()</code> to suggest the Java Virtual Machine (JVM) to perform garbage collection, which internally calls <code>Runtime.getRuntime().gc()</code>, which requests the garbage collector to trigger a garbage collection cycle, but this is not guaranteed, as the JVM manages memory independently. <code>System.gc()</code> may lead to <code>finalize()</code> being called, but only if the object is eligible for garbage collection and has a <code>finalize()</code> method.

Java also supports classes <code>java.lang.ref.Cleaner</code> and <code>java.lang.ref.PhantomReference</code> for safer low-level cleanup. <code>Cleaner</code> was introduced in Java 9 and is more efficient than <code>PhantomReference</code>, and works by registering an object with a cleaner thread which runs a cleanup action once the object is unreachable (i.e. no references to it exist). Much like <code>Closeable</code> and <code>AutoCloseable</code>, it does not reclaim memory, which is instead done by garbage collection.

<code>PhantomReference</code>, since Java 1.2, is an older cleanup mechanism that uses a reference queue. <code>PhantomReference</code> is used solely for being notified that an object's garbage collection is pending. Once the object is garbage collected, the <code>PhantomReference</code> is enqueued into the <code>ReferenceQueue</code>. Unlike <code>WeakReference</code> which can be used to access the object if it still exists in memory, <code>PhantomReference</code> can only be used for detecting when an object will be destroyed. Both <code>PhantomReference</code> and <code>WeakReference</code> do not increase reference counts.

Unlike to <code>std::weak_ptr</code> in C++ which is used to reference an object without increasing its reference count, <code>WeakReference</code> can still access the object after the reference count reaches 0, whereas in C++ <code>std::weak_ptr</code> cannot as the object is immediately destroyed once the object reaches 0 references.

Python

Python supports destructors and has a <code>del</code> keyword, but unlike <code>delete</code> in C++, <code>del</code> only decreases the reference count of the object, and does not necessarily immediately destroy the object.

Much like Java and C#, Python has a try-with-resources block, called a <code>with</code> block or a "context manager". It is used for things like files and network connections.

Rust

Rust does not have destructors in the sense of object-oriented programming, but a <code>struct</code> can implement the <code>Drop</code> trait and the <code>drop</code> method to clean itself up after it goes out of scope.

It is not possible to destroy objects explicitly through a <code>delete</code> operator like in C++, though it is possible to manually call <code>drop()</code> prematurely by using <code>std::mem::drop()</code>.

While lifetimes control the validity of references, they do not determine when <code>drop()</code> is called.

TypeScript

Although TypeScript does not have manual memory management, it has resource management similar to <code>using</code>-with-resource blocks in C# or <code>try</code>-with-resources blocks in Java, or C++ resource acquisition is initialization, that automatically close resources without need for <code>finally</code> blocks. In TypeScript, to automatically close an object, it must implement a global interface <code>Disposable</code>, and implement a method <code>Symbol.dispose()</code>. This will automatically be called at the end 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 <code>Destructor</code>. 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