Delphi TList of records

后端 未结 8 1013
遥遥无期
遥遥无期 2020-12-13 02:55

I need to store a temporary list of records and was thinking that a TList would be a good way to do this? However I am unsure how to do this with a TList<

8条回答
  •  心在旅途
    2020-12-13 03:21

    If using an older version of Delphi where generics isn't present, consider inheriting from TList and override Notify method. When adding an item, alloc memory, copy added pointer memory content and override content in list. When removing, just free memory.

      TOwnedList = class(TList)
      private
        FPtrSize: integer;
      protected
        procedure Notify(Ptr: Pointer; Action: TListNotification); override;
      public
        constructor Create(const APtrSize: integer);
      end;
    
      constructor TOwnedList.Create(const APtrSize: integer);
      begin
        inherited Create();
        FPtrSize := APtrSize;
      end;
    
      procedure TOwnedList.Notify(Ptr: Pointer; Action: TListNotification);
      var
        LPtr: Pointer;
      begin
        inherited;
        if (Action = lnAdded) then begin
          GetMem(LPtr, FPtrSize);
          CopyMemory(LPtr, Ptr, FPtrSize); //May use another copy kind
          List^[IndexOf(Ptr)] := LPtr;
        end else if (Action = lnDeleted) then begin
          FreeMem(Ptr, FPtrSize);
        end;
      end;
    

    Usage:

    ...
    LList := TOwnedList.Create(SizeOf(*YOUR RECORD TYPE HERE*));
    LList.Add(*YOU RECORD POINTER HERE*);
    ...
    
    • Note that where I did use CopyMemory(LPtr, Ptr, FPtrSize), you may use another copy aproach. My list is intended to store a record with pointer references, so it doesn't manage it's fields memory.

提交回复
热议问题