Mam taki oto kod w unicie:
unit Unit2;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TCustomer = class
private
CustomerName : String;
CustomerNumber : Integer;
public
property Name : String read CustomerName;
property Number : Integer read CustomerNumber;
constructor Create(const CustomerName : String; const CustomerNumber : Integer);
end;
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
private
myList : TList;
procedure ShowListContents;
public
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
constructor TCustomer.Create(const CustomerName : String; const CustomerNumber : Integer);
begin
self.CustomerName := CustomerName;
self.CustomerNumber := CustomerNumber;
end;
procedure TForm1.ShowListContents;
var i : Integer;
begin
for i := 0 to myList.Count-1 do
begin
ShowMessage(TCustomer(myList[i]).Name+' is customer number '+ IntToStr(TCustomer(myList[i]).Number));
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
customer : TCustomer;
begin
myList := TList.Create;
customer := TCustomer.Create('Neil Moffatt', 123);
myList.Add(customer);
customer := TCustomer.Create('Bill Gates', 64);
myList.Add(customer);
myList.Add(TCustomer.Create('Henry Cooper', 999));
myList.Add(TCustomer.Create('Alan Sugar', 2));
myList.Insert(2, TCustomer.Create('Added as item 3', 33));
myList.Delete(4);
ShowListContents;
myList.free;
end;
end.
W pliku projektu mam załączone pokazywanie wycieków pamięci
ReportMemoryLeaksOnShutdown := DebugHook <> 0;
Czy ktoś może mi wyjaśnić dla czego skąd biorą się wycieki pamięci.
Zmieniłem kod na poniższy:
procedure TForm1.FormCreate(Sender: TObject);
var
customer : TCustomer;
begin
myList := TList.Create;
customer := TCustomer.Create('Neil Moffatt', 123);
myList.Add(customer);
FreeAndNil(customer);
customer := TCustomer.Create('Bill Gates', 64);
myList.Add(customer);
FreeAndNil(customer);
myList.Add(TCustomer.Create('Henry Cooper', 999));
myList.Add(TCustomer.Create('Alan Sugar', 2));
ShowListContents;
myList.free;
end;
I mam na liście 2 Customerów o nr 999 i w sumie na liście jest ich 3.
Dla czego tak się dzieje