Destructor (computer programming)

In object-oriented programming, a destructor (sometimes abbreviated dtor[1]) is a method which is invoked mechanically just before the memory of the object is released.[2] It can happen 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. Use of destructors is needed for the process of 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 (called finalizers in this case) unsuitable for most purposes. In such languages, the freeing of resources is done either through a lexical construct (such as try..finally, Python's "with" or Java's "try-with-resources"), which is the equivalent to RAII, or explicitly by calling a function (equivalent to explicit deletion); in particular, many object-oriented languages use the Dispose pattern.

  1. ^ "dtor". TheFreeDictionary.com. Retrieved 2018-10-14.
  2. ^ Sebesta, Robert W. (2012). ""11.4.2.3 Constructors and Destructors"". Concepts of Programming Languages (print) (10th ed.). Boston, MA, USA: Addison-Wesley. p. 487. ISBN 978-0-13-139531-2.

© MMXXIII Rich X Search. We shall prevail. All rights reserved. Rich X Search