Удаление объектов, освобождение памяти
unit FreeForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
public
destructor Destroy; override;
private
Button4: TButton;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
var
B: TButton;
begin
B := TButton.Create (self);
B.Free;
// Fix: B := nil;
B.Free;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
B1, B2: TButton;
begin
// correct code
B1 := TButton.Create (self);
B2 := TButton.Create (B1); // B1 is the owner
B2.Free;
B1.Free;
end;
procedure TForm1.Button3Click(Sender: TObject);
var
B1, B2: TButton;
begin
// wrong code
B1 := TButton.Create (self);
B2 := TButton.Create (B1); // B1 is the owner
B1.Free;
B2.Free;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
// OK
Button1.Free;
end;
destructor TForm1.Destroy;
begin
Button2.Free; // OK
inherited Destroy;
Button3.Free; // OK
Button4.Free; // Error!
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Button4 := TButton.Create (self);
end;
end.
|
Загрузить весь проект
|