2
給定一個阿達保護類型:如何敲定阿達保護型
protected type A is
procedure Foo;
...
private
M : Map;
...
end A;
你將如何實現或模擬敲定過程時 保護對象最終確定是叫什麼?
基本上我需要使用受保護類型的私有成員(遍歷某個映射等)來做一些維護工作。
給定一個阿達保護類型:如何敲定阿達保護型
protected type A is
procedure Foo;
...
private
M : Map;
...
end A;
你將如何實現或模擬敲定過程時 保護對象最終確定是叫什麼?
基本上我需要使用受保護類型的私有成員(遍歷某個映射等)來做一些維護工作。
將包含在由Ada.Finalization.Controlled或Limited_Controlled派生的一個或多個記錄中的最終部分的私有成員封裝在一起。當受保護的對象最終確定後,這些私人成員也將相應地完成。
下面是一個簡單,工作示例(!):
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。
當我通過valgrind在Linux上運行這個我得到'仍然可及'類型的內存泄漏! 「仍然可以訪問:1塊中有2,104個字節」 - 這種泄漏可能來自哪裏? – NWS 2012-03-02 23:44:56