开发者

Do I have to allocate and free records when using TList<T> in Delphi?

开发者 https://www.devze.com 2022-12-27 19:44 出处:网络
The question more or less says it all.Given the following record structure: type TPerson = record Name: string;

The question more or less says it all. Given the following record structure:

type
    TPerson = record
        Name: string;
        Age: Integer;
    end;
    PPerson = ^TPerson;
    TPersonList = TList<TPerson>;

Is the following code valid?

procedure ReadPeople(DataSet: TDataSet; PersonList: TPersonList);
begin
    PersonList.Co开发者_如何学运维unt := DataSet.RecordCount;
    if DataSet.RecordCount = 0 then
        Exit;

    DataSet.First;
    while not DataSet.Eof do begin
        PersonList[DataSet.RecNo].Name := DataSet.FieldByName('Name').AsString;
        PersonList[DataSet.RecNo].Age := DataSet.FieldByName('Age').AsInteger;
        DataSet.Next;
    end;
end;

Do I have to use GetMem/FreeMem to allocate and free records an instance of TPersonList, or am I free to directly access the TPersonList entries directly? My gut says that the code should be valid, though I'm not sure if there's any wrinkles related to record initialization or finalization.


Your code's fine. When you use Tlist<T> with records, it treats them as value types, to be copied around. There's no need to allocate pointers for them.


The question is: Why do you declare PPerson? Make sure that you do not accidentally try to deallocate the memory of a TRecord from your list to which you were pointing in a PPerson variable.

0

精彩评论

暂无评论...
验证码 换一张
取 消