8

I am adding some TObject descendants to a TStringList, for example by calling AddObject. I would like them to be freed when I free the list object. Is there any way to achieve this?

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
iMan Biglari
  • 4,674
  • 1
  • 38
  • 83
  • 4
    It's a duplicate of http://stackoverflow.com/questions/9148659/how-to-free-objects-in-stringlist-in-delphi-7, but that question is poorly written. That's what's keeping me from voting to close as dupe. – Cosmin Prund Feb 18 '13 at 12:59
  • 1
    @iMan I removed the code from the question. There's not much point including that in the question since it pretty much answers the question. If you answer your own question it's best to keep the answer part in the answer. In any case, the implementation details as not needed, it's enough to refer to the documentation, as I have done in my edit to your answer. – David Heffernan Feb 18 '13 at 13:12
  • @DavidHeffernan Actually I found the answer as I was writing the question, and thought perhaps writing it here would save someone else a few minutes – iMan Biglari Feb 18 '13 at 16:39
  • Anyway, adding `OwnsObjects` to an older stringlist is not very hard – Arioch 'The Feb 19 '13 at 12:57

1 Answers1

14

The OwnsObjects property of TStringList should be set to True in order for the list to free its objects when being destroyed. This can be achieved either by calling the constructor overload that receives the OwnsObjects parameter, or by explicitly setting the property after creation. It is preferable to set OwnsObjects as part of the object's construction.

The documentation describes the property like this:

The OwnsObjects property specifies whether the string list owns the stored objects or not. If the OwnsObjects property is set to True, then the Destroy destructor will free up the memory allocated for those objects.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
iMan Biglari
  • 4,674
  • 1
  • 38
  • 83
  • is there a field for TStrings? – none Feb 18 '13 at 15:54
  • 1
    @none, if you meant, if the `OwnsObjects` property is available in `TStrings` class, then the answer is no, since this mechanism has been implemented in `TStringList`, not in its ancestor, `TStrings` class. – TLama Feb 18 '13 at 16:00