I just noticed that
var
ObjList : TObjectList <TMyObject>;
...
ObjList := TObjectList <TMyObject>.Create (True);
ObjList.Add (TMyObject.Create);
ObjList.Clear;
does not free the object. Looking at the source code it seems that no cnRemoved notification is triggered in Clear (inherited from TList <T>).
My question: Is this intentional? Is there any reason why one does not want to get these notifications in the case of Clear? Or can this be considered as a bug in the collection classes?
EDIT
Turns out that a I put the line
inherited Create;
on the top of TMyObject destructor, which was supposed to go into the constructor. This is why I got memory leaks reported that looked like the TObjectList was not freeing the items. And a look at the source convinced me (I was trapped by the Count property). Thanks for your help anyway!
The list frees owned objects when you call
.Clear. You’ve got a testing error. The code sample below, written on Delphi XE, displays this:The code in
TList<T>.Clearis deceiving, becauseCountis actually a property. Look atSetCount(), then look atDeleteRange()and you’ll see the code forNotify(oldItems[i], cnRemoved)at the end of theDeleteRangeprocedure.