types - 如何最终确定 Ada 保护类型

标签 types ada protected

给定 Ada 保护类型:

protected type A is
    procedure Foo;
    ...
private
    M : Map;
    ...
end A;

您将如何实现或模拟在以下情况下调用的Finalize过程: protected 对象已经确定了吗?

基本上,我需要使用 protected 类型的私有(private)成员进行一些内务管理(迭代某些 map 等)。

最佳答案

将参与最终确定的私有(private)成员包装在从 Ada.Finalization.Controlled 或 Limited_Controlled 派生的一个或多个记录中。当 protected 对象最终确定时,那些私有(private)成员也将相应地最终确定。

这是一个快速的、有效的(!)示例:

with Text_IO; use Text_IO;
with Ada.Finalization;
with Ada.Containers.Ordered_Maps;
with Ada.Unchecked_Deallocation;

procedure Protected_Final is

   Instance_Counter : Natural := 1;

   package Int_Map is new Ada.Containers.Ordered_Maps (Integer, Integer);
   subtype Map is Int_Map.Map;

   type Map_Wrapper is new Ada.Finalization.Controlled with record
      ID : Natural;
      M  : Map;
   end record;

   overriding procedure Initialize(Item : in out Map_Wrapper);

   overriding procedure Finalize(Item : in out Map_Wrapper);

   procedure Initialize(Item : in out Map_Wrapper) is
   begin
      Item.ID := Instance_Counter;
      Instance_Counter := Instance_Counter + 1;
      Put_Line("Initialize the Map part as instance" & Natural'Image(Item.ID));
   end Initialize;

   procedure Finalize(Item : in out Map_Wrapper) is
   begin
      Put_Line("Clean up the Map stuff for instance" & Natural'Image(Item.ID));
   end Finalize;

   protected type A is
      procedure Foo;
   private
      M : Map_Wrapper;
   end A;

   protected body A is

      procedure Foo is 
      begin
         null;
      end Foo;
   end A;

   Test_Item : A;

   type A_Handle is access A;

   procedure Free is new Ada.Unchecked_Deallocation(A, A_Handle);

   Test_Item_Handle : A_Handle;

begin
   Test_Item_Handle := new A;

   Free(Test_Item_Handle);
end Protected_Final;

运行这个我得到:

C:\sandbox\protected_final
Initialize the Map part as instance 1
Initialize the Map part as instance 2
Clean up the Map stuff for instance 2
Clean up the Map stuff for instance 1
[2011-03-04 08:37:29] process terminated successfully (elapsed time: 00.21s)

“外部”初始化/清理消息是静态声明的 Test_Item 实例的结果,而内部消息对来自动态分配和释放的 Test_Item_Handle。

关于types - 如何最终确定 Ada 保护类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5194486/

相关文章:

Java:创建作为函数参数传递的泛型类型的实例

rename - 如何重命名 protected 对象条目

java - 接口(interface)声明的访问说明符

java - 如何在 protected Java 类上实现接口(interface)

swift - 制作一个 Swift 字典,其中键是 "Type"?

python - 为什么 Python itertools 没有归类为生成器 (GeneratorType)?

c# - 为什么 C++ 和 C# 对 double 类型有不同的最大值的解释?

stream - Ada - 如何显式打包位字段记录类型?

import - Ada:导入不等式运算符 "/="

c++ - 在 Eclipse C++ 中无法识别 protected 成员