Вопрос

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?

Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top