ArticleslgStudy

computer science

Destructor (computer programming)

Destructor (computer programming) is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Destructor (computer programming) rather than just read about it. In short: 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.

Destructor (computer programming) — main illustration
Destructor (computer programming) — illustration

Key takeaways

  • Destructor (computer programming) belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Destructor (computer programming) to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Destructor (computer programming) from memory before moving on to harder problems.

Reference excerpt

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.

Worked examples

Example 1 — a first encounter with Destructor (computer programming)

Start with the simplest possible case. Write down what Destructor (computer programming) claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Destructor (computer programming) before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Destructor (computer programming) ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Destructor (computer programming)

In research
Destructor (computer programming) appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Destructor (computer programming) in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Destructor (computer programming) is common in secondary-school and first-year university syllabi. It links to neighbouring topics C++, Method (computer programming), so understanding it makes those chapters shorter.
In everyday life
Look for Destructor (computer programming) outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Destructor (computer programming)” →

How to study Destructor (computer programming) in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Destructor (computer programming) means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Destructor (computer programming) out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Destructor (computer programming) in simple terms?

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 wh…

Why does Destructor (computer programming) matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Destructor (computer programming)?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Destructor (computer programming).

Tags

  • C++
  • Method (computer programming)

Keep exploring