A special method in object-oriented programming which is invoked when an object is destroyed
In object-oriented programming, a destructor (sometimes shortened to dtor) is a method which is automatically invoked when the object is destroyed. It can happen when its lifetime is bound to scope and the execution leaves the scope, when it is embedded into 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 along its life cycle and/or deregister from other entities which may keep references to it.
In C++, the destructor (~Class
) method is core to the implementation of RAII since it is guaranteed to execute during both "normal" returns and when an exception is thrown (during stack unwinding).