Why most Delphi examples use FillChar() to initialize records?

前端 未结 8 2075
离开以前
离开以前 2020-12-13 06:32

I just wondered, why most Delphi examples use FillChar() to initialize records.

type
  TFoo = record
    i: Integer;
    s: string; // not safe in record, b         


        
相关标签:
8条回答
  • 2020-12-13 07:23

    FillChar is usually used to fill Arrays or records with only numeric types and array. You are correct that it shouldn't be used to when there are strings (or any ref-counted variables) in the record.

    Although your suggestion of using a const to initialize it would work, an issue comes into play when I have a variable length array that I want to initialize.

    0 讨论(0)
  • 2020-12-13 07:24

    This question has a broader implication that has been in my mind for ages. I too, was brought up on using FillChar for records. This is nice because we often add new fields to the (data) record and of course FillChar( Rec, SizeOf( Rec), #0 ) takes care of such new fields. If we 'do it properly', we have to iterate through all fields of the record, some of which are enumerated types, some of which may be records themselves and the resulting code is less readable as well be possibly erroneous if we dont add new record fields to it diligently. String fields are common, thus FillChar is a no-no now. A few months ago, I went around and converted all my FillChars on records with string fields to iterated clearing, but I was not happy with the solution and wonder if there is a neat way of doing the 'Fill' on simply types (ordinal / float) and 'Finalize' on variants and strings?

    0 讨论(0)
提交回复
热议问题