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<!-- except e.g. strict reference counting (see early Python) where an object is freed as soon as its refcount reaches 0-->, 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 <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>).
  • 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>java.lang.Closeable</code> (deprecated) and <code>java.lang.AutoCloseable</code>. In Java 9+, "destructors" are replaced by <code>java.lang.ref.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>std::ops::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>.

<syntaxhighlight lang=C>

  1. include <stdio.h>
  2. include <stdlib.h>

typedef struct {

void* data; // Some resource, could be anything

size_t size; // Size of the resource

} Resource;

// The "constructor"

Resource* createResource(size_t size) {

Resource* res = (Resource*)malloc(sizeof(Resource));

if (!res) {

fprintf(stderr, "Failed to allocate memory for resource.\n");

return NULL;

}

res->data = malloc(size);

if (!res->data) {

fprintf(stderr, "Failed to allocate memory for resource data.\n");

free(res);

return NULL;

}

res->size = size;

return res;

}

// The "destructor"

void destroyResource(Resource* res) {

if (res) {

if (res->data) {

free(res->data);

}

free(res);

}

}

int main() {

// Allocate the resource of 50 bytes

Resource* myResource = createResource(50);

if (!myResource) {

return 1;

}

for (size_t i = 0; i < myResource->size; ++i) {

((char*)myResource->data)[i] = (char)(i % 256); // Just some dummy data

}

printf("First 10 bytes of resource data: ");

for (size_t i = 0; i < 10; ++i) {

printf("%d ", ((char*)myResource->data)[i]);

}

printf("\n");

// Free the resource

destroyResource(myResource);

}

</syntaxhighlight>

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.

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.

<syntaxhighlight lang="cpp">

int f() {

int a = 123;

using T = int;

a.~T();

return a; // undefined behavior

}

</syntaxhighlight>

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

<syntaxhighlight lang="cpp">

import std;

using std::formatter;

using std::format_parse_context;

class Foo {

private:

size_t length;

char* data;

friend struct formatter<Foo>;

public:

// Constructor

explicit Foo(const char s[] = ""):

length{std::strlen(s)},

data{new char[length + 1]} {

std::strcpy(data, s);

}

Foo(const Foo&) = delete("Copy construction disabled");

Foo& operator=(const Foo&) = delete("Copy assignment disabled");

// Destructor

~Foo() {

delete[] data;

}

};

template <>

struct std::formatter<Foo> {

// Definition of Formatter for Foo here

};

int main(int argc, char* argv[]) {

Foo foo("Hello from the stack!");

std::println("{}", foo);

Foo* foo = new Foo("Hello from the heap!");

std::println("{}", *foo);

delete foo;

}

</syntaxhighlight>

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.

<syntaxhighlight lang="cpp">

import std;

using std::formatter;

using std::format_parse_context;

using std::unique_ptr;

class Foo {

private:

size_t length;

unique_ptr<char[]> data;

friend struct formatter<Foo>;

public:

// Constructor

explicit Foo(const char s[] = ""):

length{std::strlen(s)},

data{std::make_unique<char[]>(length + 1)} {

std::strcpy(data.get(), s);

}

Foo(const Foo&) = delete("Copy construction disabled");

Foo& operator=(const Foo&) = delete("Copy assignment disabled");

// Destructor is automatically handled by unique_ptr

~Foo() = default;

};

template <>

struct std::formatter<Foo> {

// Definition of Formatter for Foo here

};

int main(int argc, char* argv[]) {

Foo foo("Hello from the stack!");

std::println("{}", foo);

unique_ptr<Foo> foo = std::make_unique<Foo>("Hello from the heap!");

std::println("{}", *foo);

}

</syntaxhighlight>

C#

The destructor of a class <code>X</code> in C# is <code>~X()</code>, which has no parameters, and like the constructor, has no return type.

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

<syntaxhighlight lang="csharp">

namespace Wikipedia.Examples;

using System;

using System.Collections.Generic;

using System.Data.SqlClient;

public record User(int Id, string Name, string Email);

public class UserUnitOfWork : IDisposable

{

private readonly SqlConnection _connection;

private SqlTransaction _transaction;

private bool _disposed;

public UserUnitOfWork(string url)

{

_connection = new(url);

_connection.Open();

_transaction = _connection.BeginTransaction();

}

public List<User> GetActiveUsers()

{

// ...

}

public void Commit()

{

_transaction?.Commit();

}

public void Dispose()

{

if (_disposed)

{

return;

}

try

{

_transaction?.Dispose();

_connection?.Close();

_connection?.Dispose();

}

finally

{

_disposed = true;

}

}

}

class Program

{

static void Main(string[] args)

{

using (UserUnitOfWork uow = new(/* connection string */)

{

Console.WriteLine("Using UserUnitOfWork...");

List<User> users = uow.GetActiveUsers();

uow.Commit();

// ...

}

// Connection, transaction closed here

}

}

</syntaxhighlight>

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.

thumb|UML class in C# containing a constructor and a destructor.

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.

<syntaxhighlight lang="csharp">

namespace Wikipedia.Examples;

using System;

class NativeResourceHolder : IDisposable

{

private IntPtr _nativeHandle;

private bool _disposed;

public NativeResourceHolder()

{

_nativeHandle = AllocateNative();

}

public void Dispose()

{

Dispose(true);

GC.SuppressFinalize(this);

}

// The Finalizer

~NativeResourceHolder()

{

Dispose(false);

}

protected virtual void Dispose(bool disposing)

{

if (!_dipsosed)

{

// Free managed resources here, if any

}

FreeNative(_nativeHandle);

_disposed = true;

}

private IntPtr AllocateNative() => new IntPtr(42);

private void FreeNative(IntPtr ptr)

{ /* ... */ }

}

class Program

{

static void Main(string[] args)

{

NativeResourceHolder obj = new();

GC.Collect();

GC.WaitForPendingFinalizers();

Console.WriteLine("Program finished");

}

}

</syntaxhighlight>

D

The following demonstrates the usage of a destructor in D.

<syntaxhighlight lang="d">

import std.stdio;

struct Integer {

int x;

this(int value) {

x = value;

writeln("Constructor called with x = ", x);

}

~this() {

writeln("Destructor called for x = ", x);

}

}

void main() {

{

Integer s = Integer(10);

writeln("Inside scope");

} // Destructor runs here

writeln("Outside scope");

}

</syntaxhighlight>

Java

In Java there are destructors (<code>~X()</code>) like those seen in C++ and C#, but Java does provide 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>java.lang.AutoCloseable</code> may be used in a "<code>try</code>-with-resources" block, which automatically calls its <code>close()</code> method upon the end of scope, available since Java 7. Unlike destructors, however, <code>clean()</code> methods are used for resource cleanup, rather than memory deallocation, as memory is reclaimed through garbage collection.

<syntaxhighlight lang="java">

package org.wikipedia.examples;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.util.ArrayList;

import java.util.List;

public record User(int id, String name, String Email) {}

class UserUnitOfWork implements AutoCloseable {

private final Connection conn;

private bool committed = false;

public UserUnitOfWork(String url, String username, String password) throws SQLException {

this.connection = DriverManager.getConnection(url, username, password);

this.connection.setAutoCommit(false);

}

public List<User> getActiveUsers() throws SQLException {

// ...

}

public void commit() throws SQLException {

connection.commit();

committed = true;

}

@Override

public void close() throws SQLException {

try {

if (!committed) {

connection.rollback();

}

} finally {

connection.close();

}

}

}

public class Example {

public static void main(String[] args) {

try (UserUnitOfWork uow = new UserUnitOfWork(/* URL and credentials */)) {

System.out.println("Using UserUnitOfWork...");

List<User> users = uow.getActiveUsers();

uow.commit();

// ...

}

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

}

}

</syntaxhighlight>

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 the <code>finalize()</code> method of <code>java.lang.Object</code>, however this has been deprecated, as there are no guarantees which thread will invoke the <code>finalize()</code> method for any given object, or even that it will be invoked at all. Finalizers are non-deterministic (unlike destructors in C++), and releasing critical resources in a <code>finalize()</code> call may lead to unpredictable behavior..

Java has a method called <code>gc()</code> in <code>java.lang.System</code> and <code>java.lang.Runtime</code> to suggest the Java Virtual Machine (JVM) to perform garbage collection, which is internally equivalent to a <code>Runtime.getRuntime().gc()</code> call, 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.

<syntaxhighlight lang="java">

package org.wikipedia.examples;

class ParentFinalizerExample { /* ... */ }

class FinalizerExample extends ParentFinalizerExample {

@Override

protected void finalize() throws Throwable {

try {

System.out.println("finalize() called, cleaning up...");

} finally {

super.finalize(); // Always call super.finalize() to clean parent classes

}

}

}

public class Example {

public static void main(String[] args) {

FinalizerExample obj = new FinalizerExample ();

obj = null;

System.gc(); // Requests garbage collection (not guaranteed)

}

}

</syntaxhighlight>

Java also supports classes <code>java.lang.ref.Cleaner</code> and <code>java.lang.ref.PhantomReference</code> for safer low-level cleanup. <code>java.lang.ref.Cleaner</code> was introduced in Java 9 and is more efficient than <code>java.lang.ref.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>java.lang.Closeable</code> and <code>java.lang.AutoCloseable</code>, it does not reclaim memory, which is instead done by garbage collection.

<syntaxhighlight lang="java">

package org.wikipedia.examples;

import java.lang.ref.Cleaner;

import java.lang.ref.Cleaner.Cleanable;

class Resource {

private static final Cleaner cleaner = Cleaner.create();

static class State implements Runnable {

private boolean cleaned = false;

@Override

public void run() {

cleaned = true;

System.out.println("Cleaned using Cleaner");

}

}

private final State state;

private final Cleanable cleanable;

public Resource () {

this.state = new State();

this.cleanable = cleaner.register(this, state);

}

public void cleanup() {

System.gc(); // Request garbage collection (not guaranteed)

}

}

public class Example {

public static void main(String[] args) {

Resource resource = new Resource();

resource = null;

resource.cleanup();

}

}

</syntaxhighlight>

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

<syntaxhighlight lang="java">

package org.wikipedia.examples;

import java.lang.ref.PhantomReference;

import java.lang.ref.ReferenceQueue;

class Resource {

private final String name;

public Resource(String name) {

this.name = name;

}

public String getName() {

return name;

}

}

public class PhantomReferenceExample {

public static void main(String[] args) throws InterruptedException {

Resource resource = new Resource("My resource");

ReferenceQueue<Resource> queue = new ReferenceQueue<>();

PhantomReference<Resource> phantomRef = new PhantomReference<>(resource, queue);

resource = null;

System.gc();

Reference<? extends Resource> ref = queue.poll();

if (ref != null) {

System.out.printf("Object is ready to be collected: %s%n", ((PhantomReference<?>)ref).get());

}

}

}

</syntaxhighlight>

Unlike to <code>std::weak_ptr</code> in C++ which is used to reference an object without increasing its reference count, <code>java.lang.ref.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.

<syntaxhighlight lang="python">

class Destructible:

def __init__(self, name: str) -> None:

self.name: str = name

print(f"Created Destructible: {self.name}")

def __del__(self) -> None:

print(f"Destructor called for: {self.name}")

if __name__ == "__main__":

d: Destructible = Destructible("My name")

print(f"Using Destructible: {d.name}")

del d

</syntaxhighlight>

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.

<syntaxhighlight lang="python">

from typing import Optional

class Destructible:

def __init__(self, name: str) -> None:

self.name: str = name

def __enter__(self) -> "Destructible":

print(f"Entering context (allocating resource: {self.name})")

return self

def __exit__(self, exc_type: Optional[type], exc_val: Optional[Exception], exc_tb: Optional[type]) -> None:

print(f"Exiting context (cleaning up resource: {self.name})")

if __name__ == "__main__":

with Destructible("Resource A") as d:

print(f"Using resource {d.name} inside context")

  1. Most Python standard library resources support with blocks:

with open(file_path, "r") as file:

print("Reading the file content:")

content: str = file.read()

print(content)

</syntaxhighlight>

Rust

Rust does not have destructors in the sense of object-oriented programming, but a <code>struct</code> can implement the <code>std::ops::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>.

<syntaxhighlight lang="rust">

use std::mem;

struct Destructible {

name: String,

}

impl Destructible {

fn new(name: String) -> Self {

Destructible { name }

}

}

impl Drop for Destructible {

fn drop(&mut self) {

println!("Dropping Destructible: {}", self.name);

}

}

fn main() {

{

let resource_a: Destructible = Destructible::new(String::from("Resource A"));

println!("Using Destructible.");

} // <--- resource_a goes out of scope here, `drop()` is called automatically

let resource_b: Destructible = Destructible::new(String::from("Resource B"));

println!("Dropping Destructible prematurely.");

mem::drop(resource_b);

}

</syntaxhighlight>

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.

<syntaxhighlight lang="typescript">

import * as fs from 'fs';

class TempFile implements Disposable {

  1. path: string;
  2. handle: number;

constructor(path: string) {

this.#path = path;

this.#handle = fs.openSync(path, "w+");

}

write(data: string): void {

fs.writeSync(this.#handle, data);

}

[Symbol.dispose](): void {

fs.closeSync(this.#handle);

fs.unlinkSync(this.#path);

}

}

export function doSomeWork() {

using file: TempFile = new TempFile(".some_temp_file.txt");

if (someCondition()) {

// do something here

}

}

</syntaxhighlight>

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

  • new and delete (C++)
  • Finalizer
  • Constructor (computer science)
  • Object lifetime
  • Resource Acquisition Is Initialization
  • Rule of three (C++ programming)

References