1
votes

I'm trying to add a TDateTime value into a TStringList object using Delphi 10.4 Sydney.

I managed to do it like this:

TDateTimeObj = class(TObject)
strict private
  DT: TDateTime;
protected
public
  constructor Create(FDateTime: TDateTime);
  property DateTime: TDateTime read DT write DT;
end;

constructor TDateTimeObj.Create(FDateTime: TDateTime);
begin
  Self.DT := FDateTime;
end;

Then I add it to the TStringList like this:

procedure TForm1.Button1Click(Sender: TObject);
var
  b: TStringList;
begin
  b := TStringList.Create;    
  b.AddObject('a', TDateTimeObj.Create(now));    
  b.AddObject('b', TDateTimeObj.Create(now));    
  FreeAndNil(b);
end;

It works, but when I close the program I have a memory leak as I did not free the TDateTimeObj objects.

Is there a way to free the objects automatically, or a better way to achieve the same result?

1
The answer is given here.Olivier
Also, don't forget your try..finally blocks! Otherwise you'll leak on an exception, forgotten Exit etc.Andreas Rejbrand
Why don't you just use a TDictionary<string, TDateTime>? Then you don't need this wrapper class!Delphi Coder
@DelphiCoder It depends on your needs. A list is ordered, a dictionary is not.Olivier
Actually, in a 64-bit app, you can just put the TDateTime value in the object pointer.Andreas Rejbrand

1 Answers

5
votes

You have to make the string list own the added objects. Owned objects are destroyed when the string list is destroyed.

procedure TForm1.Button1Click(Sender: TObject);
var b: TStringList;
begin
  b := TStringList.Create(TRUE);     // TRUE means OwnObjects
  try
    b.AddObject('a', TDateTimeObj.Create(now));    
    b.AddObject('b', TDateTimeObj.Create(now));    
  finally
    FreeAndNil(b);                     // Owned objects will be destroyed as well
  end;
end;