1

Does ADA have an equivalent of C++'s destructors or Java's try-with-resources? That is, a technique where I can say that a resource acquired in this function is released when this function exits: whether normally or due to the handling of an exception. Is there a way to express such concept in ADA?

1

1 Answer 1

4

Consider using Ada.Finalization.Limited_Controlled (ARM 7.6, Assignment and Finalization). (why limited? because you really don’t want to copy the object you’ve created so as to release the resource).

This is a very very simple demo of the concept; release the resource at the point where I output ** finalizing a Protector **.

with Ada.Finalization;
with Ada.Text_IO; use Ada.Text_IO;

procedure Raii is

   type Protector is new Ada.Finalization.Limited_Controlled
     with null record;
   overriding procedure Finalize (Obj : in out Protector);

   procedure Finalize (Obj : in out Protector)
   is
   begin
      Put_Line ("** finalizing a Protector **");
   end Finalize;

begin

   Put_Line ("declaring a simple scope");
   declare
      P : Protector;
   begin
      Put_Line ("quitting the scope");
   end;

   Put_Line ("declaring a scope to be quit via an exception");
   begin
      declare
         P : Protector;
      begin
         Put_Line ("raising CE");
         raise Constraint_Error;
      end;
   exception
      when Constraint_Error =>
         Put_Line ("CE caught");
   end;

   Put_Line ("done.");

end Raii;

The output is

$ ./raii
declaring a simple scope
quitting the scope
** finalizing a Protector **
declaring a scope to be quit via an exception
raising CE
** finalizing a Protector **
CE caught
done.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.