Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top