I have a record containing a dynamic array. This is normal when you assign one variable of an array to another, in fact only a pointer to this array is assigned. This means that when you do this, both variables point to the same array until you resize one of them. Therefore, when I want to assign a separate copy of an array to a variable, I use the Copy () function.
In this case, however, my array is a write field:
TMyRec = record
Value: integer;
&Array: array of integer;
end;
When I declare two variables of type TMyRec and then assign them to each other, the "Array" fields in both entries will point to the same address in memory.
To solve this problem, I decided to overload the assignment operator as follows:
TMyRec = record
Value: integer;
&Array: array of integer;
public
class operator Implicit(Value: TMyRec): TMyRec;
end;
class operator TMyRec.Implicit(Value: TMyRec): TMyRec;
begin
Result := Value;
Result.&Array := Copy(Value.&Array);
end;
, TMyRecord .
:
var
Rec1, Rec2: TMyRec;
begin
Rec1.Value := 10;
SetLength(Rec1.Array, 1);
Rec2 := Rec1;
Rec2.Array[0] := 1;
end;
, ? , . ?