How to properly free records that contain various types in Delphi at once?

后端 未结 4 618
北海茫月
北海茫月 2020-11-29 19:47
type
  TSomeRecord = Record
    field1: integer;
    field2: string;
    field3: boolean;
  End;
var
  SomeRecord: TSomeRecord;
  SomeRecAr: array of TSomeRecord;
         


        
4条回答
  •  难免孤独
    2020-11-29 20:30

    Assuming you have a Delphi version that supports implementing methods on a record, you could clear a record like this:

    type
      TSomeRecord = record
        field1: integer;
        field2: string;
        field3: boolean;
        procedure Clear;
      end;
    
    procedure TSomeRecord.Clear;
    begin
      Self := Default(TSomeRecord);
    end;
    

    If your compiler doesn't support Default then you can do the same quite simply like this:

    procedure TSomeRecord.Clear;
    const
      Default: TSomeRecord=();
    begin
      Self := Default;
    end;
    

    You might prefer to avoid mutating a value type in a method. In which case create a function that returns an empty record value, and use it with the assignment operator:

    type
      TSomeRecord = record
        // fields go here
        class function Empty: TSomeRecord; static;
      end;
    
    class function TSomeRecord.Empty: TSomeRecord;
    begin
      Result := Default(TSomeRecord);
    end;
    
    ....
    
    Value := TSomeRecord.Empty;
    

    As an aside, I cannot find any documentation reference for Default(TypeIdentifier). Does anyone know where it can be found?


    As for the second part of your question, I see no reason not to continue using records, and allocating them using dynamic arrays. Attempting to manage the lifetime yourself is much more error prone.

提交回复
热议问题