Thank you for explanation Warfley.
I am interesting if in this situation strings will be free
And what will be in this situation
Yes and yes. In the first example you do not need to call SetLength(arr,0) because arrays will be freed even if you don't call setlength. When you free your array (either automatically or via setlength), all elements of that array will be freed. When the object is freed, all it's members are freed. If those are strings, or arrays or other objects records containing managed types, they will be also freed.
In your second example, when the function ends, the Object dies and therefore frees it's members. To visualize try the following:
{$mode objfpc}{$H+}
{$ModeSwitch advancedrecords}
type
TTestRec = record
x: Integer;
class operator Initialize(var r: TTestRec);
class operator Finalize(var r: TTestRec);
end;
class operator TTestRec.Initialize(var r: TTestRec);
begin
Writeln('Init ', IntPtr(@r));
end;
class operator TTestRec.Finalize(var r: TTestRec);
begin
Writeln('Final ', IntPtr(@r));
end;
type TTestObj = object r: TTestRec; end;
procedure TestObj;
var
o: TTestObj;
begin
WriteLn('TestObj ', IntPtr(@o));
end;
procedure TestArray;
var
arr: Array of TTestObj;
begin
SetLength(arr, 10);
WriteLn('After SetLength ', IntPtr(@Arr[0]));
{ Avoiding optimizer optimizing it away }
arr[0].r.x := 42;
end;
begin
WriteLn('Testing Object contining managed');
TestObj;
WriteLn('Testing array of object containing managed');
TestArray;
ReadLn;
end.
When TestObj is called with a local object variable, the managed record it contains is initialized. Once the function ends, the object is freed and with it the managed record:
Testing Object contining managed
Init 21233476
TestObj 21233476
Final 21233476
When the function with the array is called, SetLength creates 10 object instances, which all initiate it's managed field. Once the function finishes the array is freed and thereby also all the objects and their members:
Testing array of object containing managed
Init 21821496
Init 21821500
Init 21821504
Init 21821508
Init 21821512
Init 21821516
Init 21821520
Init 21821524
Init 21821528
Init 21821532
After SetLength 21821496
Final 21821496
Final 21821500
Final 21821504
Final 21821508
Final 21821512
Final 21821516
Final 21821520
Final 21821524
Final 21821528
Final 21821532
Basically the same happens with Strings, where ever call to Final would free the containing string