Destructor (computer programming)

{{short description|Function called at the end of an object's lifetime}}

In object-oriented programming, a destructor (sometimes abbreviated dtor{{Cite news|url=https://acronyms.thefreedictionary.com/dtor|title=dtor|work=TheFreeDictionary.com|access-date=2018-10-14}}) is a method which is invoked mechanically just before the memory of the object is released.{{cite book |last1=Sebesta |first1=Robert W. |title=Concepts of Programming Languages |chapter="11.4.2.3 Constructors and Destructors" |date=2012 |publisher=Addison-Wesley |location=Boston, MA, USA |isbn=978-0-13-139531-2 |page=487 |edition=10th |url=https://www.pearson.com/us/higher-education/product/Sebesta-Concepts-of-Programming-Languages-10th-Edition/9780131395312.html |language=en |format=print}} 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 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()).
  • C#: same syntax as C++. Historically called destructors, now called finalizers due to confusion.{{Cite web | url=https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/finalizers | title=Finalizers (C# Programming Guide)}}
  • D: declared as ~this() (whereas constructors are declared as this()).
  • Java: provided by 2 interfaces, Closeable and AutoCloseable. Closeable is deprecated . In Java 9+, destructors are replaced by cleaners.
  • 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.[http://www.php.net/manual/en/language.oop5.decon.php Constructors and Destructors], from PHP online documentation
  • Python: destructor method is named __del__. Called destructors in Python 2,{{Cite web |url=https://docs.python.org/2/reference/datamodel.html#object.__del__ |title=3. Data model — Python 2.7.18 documentation}} now called finalizers in Python 3.{{Cite web | url=https://docs.python.org/3/reference/datamodel.html#object.__del__ | title=3. Data model — Python 3.10.4 documentation }}
  • Rust: destructor method is named drop and is provided by the Drop trait.{{Cite web | url=https://doc.rust-lang.org/stable/reference/destructors.html | title=Destructors - the Rust Reference }}
  • Swift: destructor method is named deinit.

In 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 {{cpp|~foo()}}. 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 new and delete (C++) statement (dynamically on the heap), then its destructor is called when the delete (C++) 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.[http://www.gotw.ca/gotw/047.htm GotW #47: Uncaught exceptions] Accessed 31 July 2011.

Non-class scalar types have what's called a {{visible anchor|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.

int f() {

int a = 123;

using T = int;

a.~T();

return a; // undefined behavior

}

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.{{cite web|url=https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p0593r6.html|title=

P0593R6:Implicit creation of objects for low-level object manipulation|last1=Smith|first1=Richard|last2=Voutilainen|first2=Ville

|accessdate=2022-11-25|website=open-std.org}}

=Example=

import std;

class Foo {

public:

Foo():

data_(new char[sizeof("Hello, World!")]) {

std::strcpy(data_, "Hello, World!");

}

Foo(const Foo& other) = delete; // disable copy construction

Foo& operator=(const Foo& other) = delete; // disable assignment

~Foo(void) { delete[] data_; }

private:

friend std::ostream& operator<<(std::ostream& os, const Foo& foo) {

os << foo.data_;

return os;

}

char* data_;

};

int main() {

Foo foo;

std::cout << foo << std::endl;

}

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."Scott Meyers: Effective Modern C++, O'REILLY, {{ISBN|9781491903995}}).

File:Csharp finalizer.svg

In C with GCC extensions

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

  • The destructor function attribute[https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html#Function-Attributes C "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.{{cite book

|last = Erickson

|first = Jon

|title = Hacking the art of exploitation

|publisher = No Starch Press

|year = 2008

|isbn = 978-1-59327-144-2

}}

  • 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.{{Cite book |last=Bloch |first=Joshua |title=Effective Java |publisher=Addison-Wesley |year=2018 |isbn=978-0134685991 |edition=3rd |pages=29-31 |language=en-US}}public final class Destructors implements AutoCloseable {

@Override

public void close() { }

}

public final class Test {

try (Destructors dtors = new Destructors()) {

...

}

// after try-with-resources, dtors.close() will be called

}Prior to Java 7, a "try-finally" block was used.public final class Destructors {

public void close() { }

}

public final class Test {

try {

Destructors dtors = new Destructors();

} finally {

dtors.close()

}

}

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

References