Programming Search⌘K

Conceptcore

Destructors and finalizers

Also called destructor, finalizer, finalization, drop, cleaner, cleanup callback, object lifetime, object resurrection.

A destructor runs when an object's lifetime ends, at a point the program decides. A finalizer runs some time after a garbage collector finds the object unreachable, or never.

Applies to
core-languages

Idea

A destructor is code that runs when an object's lifetime ends, and it releases what the object holds: memory, a file, a lock or a connection. A finalizer is code that a garbage collector runs some time after it finds that an object is unreachable. The two differ in timing. A destructor runs at a point that the program text decides, such as the end of a scope or a call to delete, so the program can rely on it. A finalizer runs when the collector decides, on a thread the program does not control, and perhaps never. C++ and Rust have destructors. Java, C#, Go and JavaScript have finalizers or cleanup callbacks, and use explicit close or Dispose calls for cleanup that must happen on time. CPython has both behaviors in one mechanism.

import gc


class Resource:
    def __init__(self, name):
        self.name = name
        print("open", name)

    def __del__(self):  # runs when CPython frees the object
        print("cleanup", self.name)


def work():
    r = Resource("a")
    print("using", r.name)
    # the last reference goes when the function returns


work()
print("after work")

b = Resource("b")
b.me = b  # a cycle: the count of b never reaches zero
del b
print("after del b")
gc.collect()  # the cycle collector finds b and runs its cleanup
print("after collect")
Output
open a
using a
cleanup a
after work
open b
after del b
cleanup b
after collect

__del__ acts as a destructor for a: CPython counts references, the count reaches zero when work returns, and the cleanup runs before the next line. For b, the same method acts as a finalizer. b refers to itself, so its count never reaches zero, and the cleanup waits until the cycle collector runs. Here the program calls gc.collect, but a real program would get the cleanup at a time it cannot predict. Code that needs a file closed or a lock released at a known point cannot rely on the second case.

How it works

Destructors end a lifetime. cppreference defines the C++ form: "A destructor is a special member function that is called when the lifetime of an object ends. The purpose of the destructor is to free the resources that the object may have acquired during its lifetime."1 The compiler knows where each lifetime ends, so it inserts the call: at the end of a scope for a local variable, at the destruction of the owner for a member or an element of a container, and at delete for an object on the heap. Rust does the same through the Drop trait: "When a value is no longer needed, Rust will run a “destructor” on that value."2 Because the call point is known, a destructor can release a resource that other code waits for, which is the basis of RAII.

The order of destruction. An object can depend on objects that were created before it, so destruction runs in the reverse order of construction. Locals in a C++ or Rust scope go from last to first. Inside a C++ object, the body of the destructor runs first, while all members still exist, then the members go in the reverse order of their declaration, then the base classes. Rust drops the fields of a struct in the order of their declaration, after the struct's own drop. A destructor that runs through a pointer to a base class must be virtual in C++, or the destructors of the derived class do not run.

Finalizers come after collection. A tracing collector finds unreachable objects in batches, at times that depend on memory pressure. A finalizer runs after that, often on a separate thread. The C# documentation states it plainly: "The programmer has no control over when the finalizer is called; the garbage collector decides when to call it."3 A finalizer may also never run. MDN describes JavaScript: "A conforming JavaScript implementation, even one that does garbage collection, is not required to call cleanup callbacks."4 Python gives no guarantee for objects that still exist when the interpreter exits.5 So a finalizer must never be the only way to release a resource that matters: a program that opens files faster than the collector runs runs out of file descriptors long before it runs out of memory. See garbage collection.

Finalizers can see a broken world. When a group of objects becomes unreachable at once, the collector finalizes them in no particular order, so a finalizer cannot use the other objects of the group. The Go documentation of cleanups warns: "There is no specified order in which cleanups will run."6 A finalizer that receives the object can also store a reference to it somewhere reachable, which brings the object back to life. Python calls this resurrection: "It is possible (though not recommended!) for the del() method to postpone destruction of the instance by creating a new reference to it."5 Collectors must then check reachability again before they free the memory, which is one reason why objects with finalizers cost more to collect.

Cleanup without the object. Newer APIs avoid resurrection by never handing the object to the cleanup code. Java's Cleaner, Go's runtime.AddCleanup, JavaScript's FinalizationRegistry and Python's weakref.finalize register a separate action with the state that it needs, such as a file descriptor. The action must not refer to the object, or the object stays reachable forever. The Java documentation says: "the cleaning action must not refer to the object being registered. If so, the object will not become phantom reachable and the cleaning action will not be invoked automatically."7 Each of these APIs also lets the program run or cancel the action early, so the usual design is an explicit close that releases the resource and cancels the action, with the collector as a safety net for a forgotten close.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaStandard library
CIdiom
C#Native
JavaScriptStandard library
TypeScriptStandard libraryAs JavaScript, FinalizationRegistry for a safety net and using declarations for cleanup at the end of a block.
GoStandard library
RustNative
KotlinStandard libraryOn the JVM, java.lang.ref.Cleaner and the use function for Closeable; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLDoes not applyRows are deleted, not destroyed; ON DELETE actions and triggers are a different idea.
BashIdiomA trap on EXIT runs cleanup commands when the script ends; there are no objects.
PowerShellIdiom.NET finalizers and Dispose, with try and finally in scripts; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLIdiomThe disconnectedCallback of a custom element runs when the element leaves the document.
CSSDoes not applyCSS has no objects.
Regular expressionsDoes not applyA pattern has no objects.
Language Verdict Mechanism
Python native __del__; weakref.finalize; prompt in CPython for objects outside cycles
JavaScript stdlib FinalizationRegistry; using and Symbol.dispose
TypeScript stdlib as JavaScript
Java stdlib java.lang.ref.Cleaner; finalize deprecated
Kotlin stdlib Cleaner on the JVM; use for Closeable
C# native finalizers ~T(); IDisposable and using
Go stdlib runtime.AddCleanup, runtime.SetFinalizer; defer
Rust native Drop; std::mem::forget
C idiom destroy functions; atexit
C++ native destructors ~T()
Bash idiom trap on EXIT
PowerShell idiom .NET finalizers and Dispose
SQL n/a no objects to destroy
Regex n/a no objects
HTML idiom disconnectedCallback of custom elements
CSS n/a no objects

C++ and Rust are the languages with true destructors: the compiler inserts each call, and the order is defined. C# and Python have syntax for a cleanup method that the collector calls, and C# calls it a finalizer for this reason, although its syntax looks like a C++ destructor. Java, Go, JavaScript and Kotlin offer library APIs that register a cleanup action. In all of these languages, the cleanup that must happen on time is an explicit call: close, Dispose or a function deferred to the end of a scope. See defer and finally.

Each example file creates connections, closes them explicitly, and shows that a second close does nothing. The files for the collected languages also register a safety net and cancel it when the program closes the connection. The Rust and C++ files show the order of destruction, and the C file shows that without destructors, the caller must call each destroy function once and in the right order.

PythonGitHub
import gc
import weakref


class Conn:
    def __init__(self, name):
        self.name = name
        # A safety net: runs if the program forgets to close, at most once.
        self._finalizer = weakref.finalize(self, print, "safety net closes", name)

    def close(self):
        if self._finalizer.detach():  # cancel the safety net
            print("closed", self.name)

    def __enter__(self):
        return self

    def __exit__(self, *exc):
        self.close()


with Conn("a") as a:
    print("using", a.name)
a.close()  # a second close does nothing

b = Conn("b")
del b  # forgotten: CPython frees b now, so the safety net runs now

c = Conn("c")
c.me = c  # forgotten and in a cycle
del c
print("c is unreachable")
gc.collect()
print("end")
Output
using a
closed a
safety net closes b
c is unreachable
safety net closes c
end

This code runs but gives a wrong answer on purpose.

saved = []


class Conn:
    def __init__(self, name):
        self.name = name

    def __del__(self):
        print("finalize", self.name)
        saved.append(self)  # stores a new reference: the object comes back


c = Conn("db")
del c
print(len(saved), saved[0].name)  # the finalized object is still in use
saved.clear()  # dropped again, but CPython does not finalize it a second time
print("end")
Output
finalize db
1 db
end
  • Verdict: native. CPython frees most objects the moment their reference count reaches zero, so __del__ and weakref.finalize often run at a predictable point, as they do for b. An object in a cycle waits for the cycle collector, as c does. Other implementations, such as PyPy, use a tracing collector and run finalizers later. weakref.finalize is the safer tool: it runs at most once, detach cancels it after an explicit close, and it holds no reference to the object, so it cannot bring the object back.
  • The wrong block stores self from inside __del__. The object comes back to life after its finalizer ran, and CPython does not run __del__ again when the object dies the second time, so any cleanup in it happens only once, for an object that is still in use.
#include <iostream>
#include <memory>
#include <string>
#include <vector>

struct Noisy {
    std::string name;
    explicit Noisy(std::string n) : name(std::move(n)) { std::cout << "construct " << name << '\n'; }
    ~Noisy() { std::cout << "destroy " << name << '\n'; }
};

struct Base {
    virtual ~Base() { std::cout << "~Base\n"; } // virtual: delete through Base* is safe
};

struct Derived : Base {
    Noisy member{"member"};
    ~Derived() override { std::cout << "~Derived\n"; }
};

int main()
{
    Noisy a{"a"};
    {
        Noisy b{"b"};
        Noisy c{"c"};
        std::cout << "end of block\n";
    } // reverse order of construction: c, then b
    {
        std::unique_ptr<Base> p = std::make_unique<Derived>();
        std::cout << "end of block\n";
    } // ~Derived, then its members, then ~Base
    std::cout << "end of main\n";
}
Output
construct a
construct b
construct c
end of block
destroy c
destroy b
construct member
end of block
~Derived
destroy member
~Base
end of main
destroy a
  • Verdict: native. A destructor runs when an object's lifetime ends: at the end of the scope for a local, at delete or the destruction of a smart pointer for a heap object, and when the owner is destroyed for a member. Objects in one scope are destroyed in the reverse order of their construction. Inside an object, the body of the destructor runs first, then the members in reverse order, then the base classes.
  • A class that is deleted through a pointer to its base needs a virtual destructor in the base. Without one, delete on a Base* that points to a Derived is undefined behavior: in practice ~Derived and the destructors of its members do not run. std::unique_ptr<Base> has the same need.
JavaGitHub
import java.lang.ref.Cleaner;

public class Main {
    static final Cleaner CLEANER = Cleaner.create();

    // The state that the cleaning action needs. It must not refer to the Conn.
    record State(String name) implements Runnable {
        public void run() { System.out.println("release " + name); }
    }

    static final class Conn implements AutoCloseable {
        private final String name;
        private final Cleaner.Cleanable cleanable;

        Conn(String name) {
            this.name = name;
            this.cleanable = CLEANER.register(this, new State(name)); // a safety net
        }

        void use() { System.out.println("using " + name); }

        @Override public void close() {
            cleanable.clean(); // runs the action now, at most once
        }
    }

    public static void main(String[] args) {
        try (var a = new Conn("a")) {
            a.use();
        }
        var b = new Conn("b");
        b.use();
        b.close();
        b.close(); // the action already ran, so nothing happens
        System.out.println("end");
    }
}
Output
using a
release a
using b
release b
end
  • Verdict: stdlib. Java has no destructors, and Object.finalize is deprecated for removal. A Cleaner registers an action that runs once, either when the program calls clean or, as a safety net, after the collector finds the object phantom reachable. The action must not refer to the object, so it is a separate class, here the record State, and not a lambda or inner class that captures this. close calls clean, and try-with-resources calls close at the end of the block.
#include <stdio.h>
#include <stdlib.h>

struct conn {
    const char *name;
};

static struct conn *conn_open(const char *name)
{
    struct conn *c = malloc(sizeof *c);
    if (c != NULL) {
        c->name = name;
        printf("open %s\n", name);
    }
    return c;
}

/* The destroy function is the destructor; the caller must call it once. */
static void conn_close(struct conn *c)
{
    if (c == NULL)
        return;
    printf("close %s\n", c->name);
    free(c);
}

static void flush_logs(void) { puts("atexit: flush logs"); }
static void remove_temp(void) { puts("atexit: remove temp files"); }

int main(void)
{
    atexit(flush_logs);
    atexit(remove_temp); /* handlers run in reverse order of registration */

    struct conn *a = conn_open("a");
    struct conn *b = conn_open("b");
    conn_close(b); /* close in reverse order of opening */
    b = NULL;      /* a dangling pointer must not be used again */
    conn_close(a);
    puts("end of main");
    return 0;
}
Output
open a
open b
close b
close a
end of main
atexit: remove temp files
atexit: flush logs
  • Verdict: idiom. C has no destructors and no finalizers. Each type that owns memory or a resource comes with a destroy function, such as conn_close, and the caller must call it exactly once, in the reverse order of creation when one object depends on another. A pointer to a destroyed object must not be used again, and setting it to NULL makes a later mistake easier to find. atexit registers functions that run when the program exits normally, in the reverse order of registration.
using (var a = new Conn("a"))
{
    a.Use();
}

var b = new Conn("b");
b.Use();
b.Dispose();
b.Dispose();  // a second call does nothing
Console.WriteLine("end");

// The dispose pattern: Dispose for the program, a finalizer as a safety net.
class Conn : IDisposable
{
    private readonly string name;
    private bool disposed;

    public Conn(string name) => this.name = name;

    public void Use() => Console.WriteLine($"using {name}");

    public void Dispose()
    {
        Dispose(disposing: true);
        GC.SuppressFinalize(this);  // the finalizer has nothing left to do
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposed) return;
        disposed = true;
        // When disposing is false, the finalizer is running: other managed objects
        // may already be finalized, so release only unmanaged resources.
        Console.WriteLine($"release {name} (disposing: {disposing})");
    }

    ~Conn() => Dispose(disposing: false);
}
Output
using a
release a (disposing: True)
using b
release b (disposing: True)
end
  • Verdict: native. A C# class can declare a finalizer with the syntax ~Conn(), which the garbage collector calls at a time it chooses, on a separate thread. The dispose pattern pairs it with Dispose: the program calls Dispose, often through using, and GC.SuppressFinalize tells the collector that the finalizer has nothing left to do. When the finalizer runs, disposing is false, and the method must not touch other managed objects, because the collector may have finalized them already. Most classes need no finalizer: a SafeHandle wraps an operating system handle and has its own.
JavaScriptGitHub
"use strict";

// The callback may run some time after a Conn is collected, or never.
const registry = new FinalizationRegistry((name) => {
  console.log("safety net closes", name);
});

class Conn {
  #closed = false;

  constructor(name) {
    this.name = name;
    // The held value is the name, not the Conn: the callback must not keep it alive.
    registry.register(this, name, this);
  }

  close() {
    if (this.#closed) return;
    this.#closed = true;
    registry.unregister(this); // the program closed it: cancel the safety net
    console.log("closed", this.name);
  }

  [Symbol.dispose]() {
    this.close();
  }
}

const a = new Conn("a");
console.log("using", a.name);
a.close();
a.close();
console.log(registry.unregister(a)); // nothing left to cancel

{
  using b = new Conn("b"); // closed at the end of the block
  console.log("using", b.name);
}
console.log("end");
Output
using a
closed a
false
using b
closed b
end
  • Verdict: stdlib. JavaScript has no destructors. FinalizationRegistry calls a callback some time after a registered object is collected, but an engine may call it late or never, so it can only be a safety net. The held value passed to the callback must not be the object itself, or the object stays reachable. Passing the object as the unregister token lets close cancel the callback. A using declaration calls [Symbol.dispose] at the end of its block, which gives deterministic cleanup.
package main

import (
	"fmt"
	"runtime"
)

type handle struct{ name string } // the underlying resource

func release(h *handle) { fmt.Println("release", h.name) }

type Conn struct {
	h       *handle
	cleanup runtime.Cleanup
}

func Open(name string) *Conn {
	c := &Conn{h: &handle{name}}
	// A safety net: the argument is the handle, not c, so c can still be collected.
	c.cleanup = runtime.AddCleanup(c, release, c.h)
	return c
}

func (c *Conn) Close() {
	if c.h == nil {
		return
	}
	c.cleanup.Stop() // the program closed it: cancel the safety net
	release(c.h)
	c.h = nil
}

func main() {
	a := Open("a")
	defer a.Close() // runs when main returns
	fmt.Println("using", a.h.name)

	b := Open("b")
	b.Close()
	b.Close() // a second call does nothing
	fmt.Println("end of main")
}
Output
using a
release b
end of main
release a
  • Verdict: stdlib. Go has no destructors. defer runs Close when the function returns, and runtime.AddCleanup attaches a function that runs some time after an object is unreachable, in a separate goroutine. The cleanup receives the handle, not the Conn, because a cleanup that can reach its object keeps it alive forever. Stop cancels the cleanup after an explicit close. The older runtime.SetFinalizer passes the object itself to the finalizer, which can then bring it back to life.
RustGitHub
struct Noisy(&'static str);

impl Drop for Noisy {
    fn drop(&mut self) {
        println!("drop {}", self.0);
    }
}

struct Pair {
    first: Noisy,
    second: Noisy,
}

fn main() {
    let _a = Noisy("a");
    let _b = Noisy("b"); // locals drop in reverse order: b, then a
    {
        let p = Pair {
            first: Noisy("p.first"),
            second: Noisy("p.second"),
        };
        println!("end of block with {} and {}", p.first.0, p.second.0);
    } // fields drop in declaration order
    let v = vec![Noisy("v0"), Noisy("v1")];
    drop(v); // drop early; elements drop in order
    let c = Noisy("c");
    std::mem::forget(c); // never dropped: forgetting is safe, only a leak
    println!("end of main");
}
Output
end of block with p.first and p.second
drop p.first
drop p.second
drop v0
drop v1
end of main
drop b
drop a

This code does not compile, on purpose. The error is E0040.

struct Noisy(&'static str);

impl Drop for Noisy {
    fn drop(&mut self) {
        println!("drop {}", self.0);
    }
}

fn main() {
    let a = Noisy("a");
    a.drop(); // a second drop would run at the end of the scope
}
  • Verdict: native. A type that implements Drop has a destructor, and the compiler inserts the call where the value's owner goes away. Local variables drop in the reverse order of their declaration, the fields of a struct in the order of their declaration, and the elements of a Vec from first to last. drop(v) moves the value into a function that ends at once, which drops it early. std::mem::forget skips the destructor; Rust treats a leak as safe, so code must not rely on a destructor to keep memory safe.
  • The failing block calls the drop method directly. The compiler rejects this with error E0040, because the value would be dropped again at the end of its scope. Call drop(a) instead, which takes the value by move.
  • Dispose and close. IDisposable, AutoCloseable, io.Closer and the context manager protocol give a method for explicit cleanup, which using, try-with-resources, defer and with call at the end of a block.
  • Reference counting. CPython, Swift and std::shared_ptr run the cleanup when the last reference goes, which makes the time predictable except for cycles. See reference counting.
  • Weak and phantom references. A weak reference lets a program notice that an object was collected. Java's phantom references and reference queues are the machinery under Cleaner.
  • Ownership. Rust moves ownership so that each value has exactly one owner, and the destructor runs when that owner goes away. See ownership.
  • Linear and affine types. A type that must be used exactly once can force a program to call a specific function to destroy it, which some research languages explore.
  • Construction. Destruction mirrors construction: the object is built bases first and members in order, and taken apart in reverse. See constructors.
  • Process exit. The operating system reclaims memory, files and sockets when a process ends, so some programs skip their destructors at exit to save time. Handlers registered with atexit, and destructors of static objects in C++, run at a normal exit.

Pitfalls

  • Relying on a finalizer for a scarce resource. Files, sockets and locks can run out before the collector runs. Close them explicitly, and keep the finalizer as a safety net only.
  • A cleanup that refers to its object. A lambda or inner class that captures this keeps the object reachable, so the cleanup never runs. The Java, Go and JavaScript files pass only the state that the cleanup needs.
  • Resurrection. A finalizer that stores its object makes it reachable again, and the finalizer does not run a second time. The wrong block in the Python file shows this.
  • Exceptions from destructors. A C++ destructor that throws during stack unwinding ends the program with std::terminate, and exceptions from Java cleaning actions and Python __del__ are ignored. Report errors from cleanup in another way, or give the class an explicit close that can fail.
  • Missing virtual destructor. In C++, delete through a pointer to a base class without a virtual destructor is undefined behavior. Declare the destructor of a polymorphic base class virtual.
  • Use after destruction. A pointer or reference that outlives its object leads to use after free in C and C++. Rust's borrow checker rejects such code.
  • Double destruction. Calling a destroy function twice in C, or calling a destructor explicitly in C++ and then letting the scope end, destroys the object twice. Make close safe to call twice, as every example file does.
  • Leaks through forgotten cleanup. A forgotten destroy call in C, a std::mem::forget in Rust, or a reference cycle leaks the resource. See memory leaks.

Cost

A destructor costs a call and the work it does, and compilers inline small ones; a type without a destructor costs nothing at the end of its lifetime. A virtual destructor adds an indirect call. Finalizers cost more: the collector must track each object that has one, keep it alive for one more cycle so that the finalizer can run, and run the finalizers on a separate thread. Objects with finalizers therefore survive longer and slow down collection. Cleanup actions in the style of Cleaner cost a registration and a small extra object for each registered object, and cancelling an action after an explicit close removes most of the collector's extra work.

History

C with Classes, from 1980, had a function that ran when an object was destroyed, and C++ named it the destructor and gave it the syntax ~T(). Java 1.0, in 1996, gave every object a finalize method, and C#, from 2002, borrowed the syntax of C++ destructors for its finalizers, which its documentation later renamed to reflect their behavior.3 Experience showed the problems of finalizers: unpredictable timing, resurrection and slow collection. Java 9 deprecated finalize in 2017 and added Cleaner, and Java 18 deprecated finalization for removal in 2022.7

Python 3.4, in 2014, made the cycle collector able to free cycles of objects with __del__ methods, and added weakref.finalize. Rust, from 2015, gave types destructors through Drop; shortly before its first stable release, its designers made std::mem::forget safe, after they found that reference cycles could leak values without it. ECMAScript 2021 added WeakRef and FinalizationRegistry to JavaScript.4 Go 1.24, in 2025, added runtime.AddCleanup as a safer alternative to runtime.SetFinalizer.6

References

  1. Destructors, cppreference.com, Explanation
  2. Trait Drop, The Rust Standard Library, Drop; Drop order
  3. Finalizers, C# programming guide, Microsoft Learn, Remarks
  4. FinalizationRegistry, MDN Web Docs, Notes on cleanup callbacks
  5. Data model, The Python Language Reference, 3.3.1 Basic customization, object.__del__
  6. Package runtime, Go standard library, func AddCleanup
  7. Cleaner, Java SE 25 API documentation, Class Cleaner

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/D6D0AW/text.yaml