Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to allocate and deallocate a dynamic list in Delphi?

I'm new to Delphi and trying to figure out how to deal with memory management. I have a class, TFileData, that is dynamically allocated and put into a list. Every time I reload data from files I need to release the old objects and allocate new.

To allocate I use this function:

function TImportXmlForm.GetLanguageFileData: TList<TFileData>;
begin
  if FAllFiles = nil then
    FAllFiles := TList<TFileData>.Create;
  Result := FAllFiles;
end{function};

To deallocate:

if Assigned(FAllFiles) then
begin
  while FAllFiles.Count > 0 do
  begin
    FAllFiles.Items[0].Free;
    FAllFiles.Delete(0);
  end;
  FAllFiles.Free;
  FAllFiles := nil;
end{if};

What is the "best practice" for this kind of programming patterns?

like image 789
David Avatar asked Jan 14 '23 05:01

David


1 Answers

Use TObjectList<T> instead of TList<T>.

By default TObjectList<T> will free the object when you delete it from the list or all objects when you free the objectlist itself. This is controlled by the OwnsObjects parameter of the constructor which is by default True.

like image 135
whosrdaddy Avatar answered Jan 22 '23 10:01

whosrdaddy