When emptying an array, is there any difference that one should be aware of between the following alternatives?
Assuming arr is a TArray<string>:
SetLength(arr, 0);
or
arr := [];
I'm guessing they are the same, but my Delphi is a bit rusty and I seem to recall subtle "peculiarities" coming back to haunt me after months of seemingly working code before...
CodePudding user response:
If arr is a dynamic array variable, then
SetLength(arr, 0)
and
arr := nil
and the new (Delphi XE7 )
arr := []
are all equivalent.
The key to understand this equivalence is the following part from the SetLength documentation:
Following a call to
SetLength,Sis guaranteed to reference a unique string or array -- that is, a string or array with a reference count of one.
Also, recall that an empty dynamic array is represented by a nil pointer, and not a pointer to a "length-zero dynamic array heap object":
When the variable is empty (uninitialized) or holds a zero-length array, the pointer is
niland no dynamic memory is associated with the variable.
