In Delphi 2009, I had no major problems with Generics so far (using Generics.Collections lists, with no special Generics features).
Now I found this code will cause a ‘Invalid pointer operation’ in the line which accesses MyList.Count. (MyList.Contains and MyList.IndexOf cause the same error).
The error disappears if I declare TMyList = class(TList<TMyEntry>);
Should I avoid TObjectList<T> or is something else in my code causing this error?
type
TMyEntry = class(TStringlist);
TMyList = class(TObjectList<TMyEntry>);
procedure TListTests.TestAV;
var
Entry: TMyEntry;
MyList: TMyList;
begin
MyList := TMyList.Create;
try
Entry := TMyEntry.Create;
try
MyList.Add(Entry);
Assert(MyList.Count = 1); // <--- fails
finally
Entry.Free;
end;
finally
MyList.Free;
end;
end;
TObjectListnamed Object List because it owns objects wich it stores. so you have not to free objects wich list contains yourself.TObjectListdoes it for you.I’ve tested you example code in Delphi2010. And I get AV in
MyList.free()line. the reason is that you doEntry.Free. List doesn’t know about this, and tries tofreeobject again.TObjectLists constructor has boolean parametrerownsObjects(default = true), you can use it and free objects, wich it contains manually.