說我的表格在TFormOther = class(TForm, IMyInterface)哪里
type
IMyInterface = interface
['{50E7E215-A8EA-4A1C-9F1E-018E4A76DCBD}']
procedure DoSomething;
end;
和
TFactory = class(TInterfacedObject)
public
procedure MakeIt;
end;
procedure TFactory.MakeIt;
var
LMyIntf: IMyInterface;
begin
LMyIntf := TFormOther.Create(nil);
LMyIntf.DoSomething;
// (LMyIntf as TFormOther).Free; This is wrong and gives the classic:
// FastMM has detected an attemp to use an interface of a freed object.
end;
如果我不釋放 TFormOther 實體,我會泄漏記憶體。
我知道我可以做到Action := TCloseAction.caFree,TFormOther.FormClose但這是唯一也是最好的方法嗎?
當沒有更多參考時,介面實作表單會自行釋放嗎?幫助很大,但沒有說應該如何釋放表格。
uj5u.com熱心網友回復:
通過其介面參考直接釋放表單的問題(LMyIntf as TFormOther).Free;是介面參考將超過表單物件實體。
當該介面超出范圍時,在程序尾聲中,編譯器插入_IntfClear對完成LMyIntf參考的呼叫最終將最終呼叫_Release已銷毀的表單實體上的方法。
為避免這種情況,您必須先明確清除界面,然后才能自由形式。這需要額外的物件變數,您可以通過它呼叫Free來釋放表單。
procedure TFactory.MakeIt;
var
LMyIntf: IMyInterface;
LObj: TObject;
begin
LMyIntf := TFormOther.Create(nil);
LMyIntf.DoSomething;
LObj := TObject(LMyIntf);
LMyIntf := nil;
LObj.Free;
end;
當通過FromClose事件處理程式發布表單時,只有在發布時沒有對表單的活動介面參考,這種發布才能完美地作業。在討論通用代碼時很難說哪種方法更好,但是在使用FormClose事件時,可能更難確保您此時沒有活動界面,并且此類代碼可能更難遵循。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/517052.html
