ฉันกำลังส่งวัตถุที่สร้างขึ้นไปยังตัวสร้างของวัตถุอื่นซึ่งต้องการอินเทอร์เฟซที่วัตถุนั้นนำไปใช้
ISomeInterface = interface
['{840D46BA-B9FB-4273-BF56-AD0BE40AA3F9}']
end;
TSomeObject = class(TInterfacedObject, ISomeinterface)
end;
TSomeObject2 = class
private
FSomeInterface: ISomeinterface;
public
constructor Create(SomeObject: ISomeInterface);
end;
var
Form1: TForm1; // main form
SomeObject: TSomeObject;
constructor TSomeObject2.Create(SomeObject: ISomeInterface);
begin
FSomeInterface := SomeObject;
end;
// main form creating
procedure TForm1.FormCreate(Sender: TObject);
var SomeObject2: TSomeObject2;
begin
SomeObject := TSomeObject.Create;
// SomeObject2 := TSomeObject2.Create(nil); // ok
SomeObject2 := TSomeObject2.Create(SomeObject); // not ok
try
// do some things
finally
SomeObject2.Free;
end;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
SomeObject.Free; // if passed to a SomeObject2 Constructor - freeing it causing av
end;
หลังจากที่ฉันปิดฟอร์มหลัก มันทำให้ฉันมี AV และหน่วยความจำรั่ว - ฟอร์มหลักทั้งหมดรั่วไหล ถ้าฉันส่ง nil
ไปยังตัวสร้าง TSomeObject
ทุกอย่างก็ดี ตัวคอมไพเลอร์ทำให้ว่าง FSomeInterface
โดยการนับอ้างอิงและฉันไม่ควรพยายามปล่อย SomeObject
ใน mainForm destructor
หรือไม่ ฉันจะหลีกเลี่ยงมันได้อย่างไร?