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 Answer
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.