在Ada(2005或2012)中实现相当于java finalize块的最佳实践

前端之家收集整理的这篇文章主要介绍了在Ada(2005或2012)中实现相当于java finalize块的最佳实践前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Java具有finalize块,允许在块之后执行一些语句
保留(即使引发异常也会执行).例:
try {
  ...
} catch (Exception e) {
  ...
} finally {
  ... // any code here
}

Ada具有允许实现Finalize操作的受控对象
但是没有与java中相同的finalize块.这对于日志记录非常有用
关闭文件,事务等(无需为每个可能的块创建特定的标记类型).

>你将如何在Ada 2005中实现这样的终结块(同时保持代码可读)?
> Ada 2012是否有计划允许轻松执行任何终结代码

解决方法

我相信这段代码会按照你的要求行事;它成功打印出目前加注或返回的42.这是T.E.D建议的实施.

在Mac OS X,Darwin 10.6.0上使用GCC 4.5.0进行测试.

with Ada.Finalization;
package Finally is

   --  Calls Callee on deletion.
   type Caller (Callee : not null access procedure)
      is new Ada.Finalization.Limited_Controlled with private;

private

   type Caller (Callee : not null access procedure)
      is new Ada.Finalization.Limited_Controlled with null record;

   procedure Finalize (Object : in out Caller);

end Finally;


package body Finally is

   procedure Finalize (Object : in out Caller)
   is
   begin
      Object.Callee.all;
   end Finalize;

end Finally;


with Ada.Text_IO; use Ada.Text_IO;
with Finally;
procedure Finally_Demo is
begin

   declare

      X : Integer := 21;

      --  The cleanup procedure,to be executed when this block is left
      procedure F
      is
      begin
         Put_Line ("X is " & Integer'Image (X));
      end F;

      --  The controlled object,whose deletion will execute F
      F_Caller : Finally.Caller (F'Access);

   begin

      X := 42;

      raise Constraint_Error;

   end;

end Finally_Demo;
原文链接:https://www.f2er.com/java/239812.html

猜你在找的Java相关文章