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 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.
© MMXXIII Rich X Search. We shall prevail. All rights reserved. Rich X Search