问题描述
Java具有finalize块,该块允许在剩下
块之后执行一些语句(即使引发异常也被执行)。例如:
Java has the finalize block which allows to execute some statements after a blockis left (executed even if an exception is raised). Example:
try {
...
} catch (Exception e) {
...
} finally {
... // any code here
}
Ada具有可实现 Finalize 操作
的受控对象,但是没有与Java中等效的finalize块。这对于日志记录,
关闭文件,事务等(无需为每个可能的块创建特定的标记类型)很有用。
Ada has the controlled objects which allows to implement a Finalize operationbut there is no finalize block equivalent as in java. This is useful for logging,closing files, transactions and so on (without having to create a specific tagged type for each possible block).
- 您如何在Ada 2005中实现这样的finalize块(同时保持代码可读性?)?
- Ada 2012中是否有计划允许轻松执行任何finalization代码?
推荐答案
我相信这段代码将满足您的要求;它会成功打印出 42
并显示当前的收入
或返回返回
。
I believe this code will do what you ask; it successfully prints out 42
with the present raise
or with return
. It's an implementation of T.E.D's suggestion.
在Mac OS X,Darwin 10.6.0上使用GCC 4.5.0进行了测试。
Tested with GCC 4.5.0 on Mac OS X, Darwin 10.6.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;
这篇关于在Ada(2005或2012)中实现等效于Java finalize块的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!