17.3.13 Destructors

The Destructor extension adds a new finalization mechanism that significantly differs standard Ada in how it interacts with type derivation.

New syntax is introduced to make it possible to define “destructors” for record types, tagged or untagged. Here’s a simple example:

package P is
   type T is record
      ...
   end record;

   procedure T'Destructor (X : in out T);
end P;
package body P is
   procedure T'Destructor (X : in out T) is
   begin
      ...
   end T'Destructor;
end P;

Like Finalize procedures, destructors are called on objects just before they are destroyed. But destructors are more flexible in how they can used with derived types. With standard Ada finalization, when you derive from a finalizable type, you must either inherit the Finalize procedure or override it completely.

Destructors work differently. You can define a destructor for a type derived from a parent type that also has a destructor, and then when objects of the derived type are finalized, both destructors will be called. For example:

type T1 is record
   ...
end record;

procedure T1'Destructor (X : in out T1);

type T2 is new T1;

procedure T2'Destructor (X : in out T2);

When an object of type T2 is finalized, there will be first a call to T2'Destructor, and then a call to T1'Destructor on the object.