How to free a generic TList<T>?
Asked Answered
S

1

31

Does freeing generic lists like TList<string>, TList<Double>, TList<Integer> or TList<TMyRecord>, where TMyRecord is declared like:

type
  TMyRecord = record
    MyString: string;
    MyDouble: Double;
    MyInteger: Integer;
  end;

require any additional work or is MyList.Free sufficient ?

Suite answered 29/3, 2013 at 16:8 Comment(1)
+1. Very nicely written question.Igorot
L
33

Executive summary

MyList.Free is sufficient.

Detailed answer

The TList<T> generic container owns its contents. When you free the container, the contents are also disposed of.

Now, if T is an unmanaged reference, either a pointer or a class, then the list owns the reference. It does not own that which the reference refers to. So if you have TList<TObject>, add some objects, and then free the list, the references are disposed of, but the objects remain. So, to deal with this there is TObjectList<T>. That container can be configured to own the objects as well as the references, and so dispose of the objects at the appropriate moment.

Now, in your scenario, each of your lists contains either a value type, or a managed type. The list owns those objects and disposes of them when it is destroyed. So for all of your lists, MyList.Free is all that is needed.

Lutero answered 29/3, 2013 at 16:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.