Delphi: TObjectList won't free object after Delete() is called

812 Views Asked by At

I have a TObjectList<TUSBDevice>, where TUSBDevice is a class I've made. I tried calling Delete with the index passed as a parameter but that it simply does what TList.Delete() does: removes the pointer from the list but doesn't free the object itself.

The breakpoint I placed on TUSBDevice.Destroy() doesn't break when Delete() is called. I also had a watch on the TObjectList and I can see the item gets removed from the list but the contents at the memory address of the object don't get freed.

Destructor of TUSBDevice:

destructor TUSBDevice.Destroy();
begin
  removeDatabaseEntry();
  filteredFolders.Free();
  fileQueue.Free();
end;
2

There are 2 best solutions below

6
Andreas Rejbrand On BEST ANSWER

It's impossible to answer your question since it doesn't contain a minimal reproducible example; the issues doesn't lie in the code you posted, but elsewhere.

Still, the most common cause of an "overridden" destructor not running is that it is in fact not overridden. So I can almost bet that your Destroy declaration is missing the override:

TUSBDevice = class
  // ...
public
  // ...
  destructor Destroy; override;
  // ...
end;
1
Juan C.Cilleruelo On

Immediately after creating a TObjectList member, you must change his property OwnsObjects to True. This allows the destruction of the objects linked to the Object List when no more is necessary. (i.e., when you delete a member or when you free the TObjectList member)

Pieces := TObjectList<TPiece>.Create;
Pieces.OwnsObjects := True;