那么,你应该Adjust
适当地实施!
当您制作副本时,它是按位复制的,因此原始文件中的任何指针都会按原样复制到副本中。当原始文件完成并释放指向的对象时,副本中会留下一个指向超空间的指针。
要做的是分配一个新指针,指定与原始指针相同的值。就像是
with Ada.Finalization;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Unchecked_Deallocation;
procedure Finalart is
type Integer_P is access Integer;
type Controlled_Type is new Ada.Finalization.Controlled with record
P : Integer_P;
end record;
procedure Initialize (This : in out Controlled_Type);
procedure Adjust (This : in out Controlled_Type);
procedure Finalize (This : in out Controlled_Type);
procedure Initialize (This : in out Controlled_Type) is
begin
Put_Line ("initialize");
This.P := new Integer'(42);
end Initialize;
procedure Adjust (This : in out Controlled_Type) is
Original_Value : constant Integer := This.P.all;
begin
Put_Line ("adjust");
This.P := new Integer'(Original_Value);
end Adjust;
procedure Finalize (This : in out Controlled_Type) is
procedure Free is new Ada.Unchecked_Deallocation (Integer, Integer_P);
begin
Put_Line ("finalize");
Free (This.P);
end Finalize;
function Create return Controlled_Type is
CT : Controlled_Type;
begin
Put_Line ("check 1");
return CT;
end Create;
Bar : Controlled_Type := Create;
begin
Put_Line ("check 2");
end Finalart;
如果我注释掉 中的行This.P := new Integer'(Original_Value);
,Adjust
我会得到(在 macOS 上)
$ ./finalart
initialize
check 1
adjust
finalize
adjust
finalize
finalart(35828,0x7fffd0f8b3c0) malloc: *** error for object 0x7fca61500000: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
raised PROGRAM_ERROR : unhandled signal