我該如何改變我的析構函數來處理共享對象實例?如何更改Delphi析構函數來處理共享對象實例?
實施例:
type
TAddress = class
private
FStreet : String;
public
property street: String read FStreet write FStreet;
end;
TContract = class
private
FAddress : TAddress;
public
property address: TAddress read FAddress write FAddress;
destructor Destroy; override;
end;
Array_Of_TContract = array of TContract;
TCustomer = class
private
FContracts : Array_Of_TContract;
public
property contracts: Array_Of_TContract read FContracts write FContracts;
destructor Destroy; override;
end;
implementation
destructor TCustomer.Destroy;
var
I: Integer;
begin
for I := 0 to System.Length(FContracts)-1 do
SysUtils.FreeAndNil(FContracts[I]);
System.SetLength(FContracts, 0);
inherited Destroy;
end;
destructor TContract.Destroy;
var
I: Integer;
begin
SysUtils.FreeAndNil(FAddress);
inherited Destroy;
end;
begin
Try
//address
myAddress := TAddress.Create;
myAddress.street := 'My Street';
//First contract
SetLength(myContracts, Length(myContracts)+1);
FirstContract := TContract.Create;
FirstContract.address := myAddress; //<-
myContracts[0] := FirstContract;
//Second contract
SetLength(myContracts, Length(myContracts)+1);
SecondContract := TContract.Create;
SecondContract.address := myAddress; //<-
myContracts[1] := SecondContract;
//Single customer
myCustomer := TCustomer.Create;
myCustomer.contracts := myContracts;
myCustomer.Free;
self.Close;
Except
On e: exception do begin
ShowMessage(e.Message);
end;
End;
end;
釋放myCustomer(和內存泄漏)時的結果是無效的指針操作。
(創建每個TContract單獨TAddress對象是不是在我的情況選擇)
個人更喜歡界面選項 - 它有效地爲您實現引用計數和垃圾收集 –