Author: KK Gian Gian
How can I prevent resources leak.
Answer:
Make use of Interface characteristic where when the reference goes out of scope it
will free itself.
1 type2 IAutoClean = interface3 ['{61D9CBA6-B1CE-4297-9319-66CC86CE6922}']
4 end;
5 6 TAutoClean = class(TInterfacedObject, IAutoClean)
7 private8 FObj: TObject;
9 public10 constructor Create(AObj: TObject);
11 destructor Destroy; override;
12 end;
13 14 implementation15 16 constructor TAutoClean.Create(AObj: TObject);
17 begin18 FObj := AObj;
19 end;
20 21 destructor TAutoClean.Destroy;
22 begin23 FreeAndNil(FObj);
24 inherited;
25 end;
26 27 Application....
28 29 procedure TForm1.Button1Click(Sender: TObject);
30 var31 a: IAutoClean;
32 //must declare as local variable, so when this procedure finished, it's out of 33 scope
34 o: TOpenDialog; //any component35 begin36 o := TOpenDialog.Create(self);
37 a := TAutoClean.Create(o);
38 if o.Execute then39 ShowMessage(o.FileName);
40 end;