gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:55:33 26 4
gpt4 key购买 nike

给定 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com