While working on a small generic collection library in Delphi, I encountered some unexpected behavior during the early development of a new type. It involved an implicit conversion operator, a record containing a managed dynamic array, and assignment to an existing variable.
The issue was straightforward: assigning an empty array to a sequence didn't clear its existing contents.
What surprised me was why the problem appeared to occur.
The record
I have a generic record, TSequence<T>, which stores its elements in a dynamic array:
TSequence<T> = record
private
fItems: TArray<T>;
public
function GetEnumerator: TSequenceEnumerator<T>;
class operator Implicit(const aSource: array of T): TSequence<T>;
end;
The intention is simple. An array can be implicitly converted into a sequence, with the sequence maintaining its own copy of the elements. For example:
var sequence: TSequence<Integer> := [1, 2, 3, 4];
for var item in sequence do
Writeln(item);
So far, everything works as expected.
The original implementation
My original conversion operator handled empty arrays with an early exit:
class operator TSequence<T>.Implicit(const aSource: array of T): TSequence<T>;
begin
if Length(aSource) = 0 then exit;
SetLength(Result.fItems, Length(aSource));
for var i := 0 to High(aSource) do
Result.fItems[i] := aSource[i];
end;
At first glance, this seemed reasonable.
If the source is empty, the resulting sequence should also be empty. Since fItems is a managed dynamic array, I expected it to be initialized to nil, giving it a length of zero.
However, consider what happens when we subsequently assign an empty array:
var sequence: TSequence<Integer> := [1, 2, 3, 4];
for var item in sequence do
Writeln(item);
sequence := [];
After the final assignment, I expected sequence to be empty.
Instead, it still contained the original four elements.
Investigating Result
I removed the early exit and added a guard to check the state of the result record on entry:
class operator TSequence<T>.Implicit(const aSource: array of T): TSequence<T>;
begin
Assert(Length(Result.fItems) = 0);
SetLength(Result.fItems, Length(aSource));
for var i := 0 to High(aSource) do
Result.fItems[i] := aSource[i];
end;
The assertion failed when assigning the empty array to the existing sequence.
In other words, at the point where the conversion operator began executing, Result.fItems already appeared to contain the destination record's previous array.
That wasn't what I expected.
What is going on here?
Wondering whether age might be catching up with me, I decided to double-check my understanding that managed fields of records are initialized by default. Specifically, I expected the array field to be nil when the record was initialized.
According to Embarcadero's documentation:
- Custom Managed Records explains that the compiler automatically manages the initialization and finalization of records containing managed fields.
- Internal Data Formats confirms that an uninitialized or zero-length dynamic array has a nil pointer.
So something is not right here. Perhaps this is another case of compiler elision causing a subtle bug?
In a previous post, I explored a related issue where the compiler constructed the result directly in the assignment target.
The fix
Fortunately, the practical fix was simple: always assign the result's state, even when the source is empty.
class operator TSequence<T>.Implicit(const aSource: array of T): TSequence<T>;
begin
SetLength(Result.fItems, Length(aSource));
for var i := 0 to High(aSource) do
Result.fItems[i] := aSource[i];
end;
Now:
sequence := [];
correctly produces an empty sequence.
The unconditional SetLength ensures that the resulting array has the required length, regardless of its previous state.
Final thoughts
The immediate problem is resolved, but I'm still curious about the underlying behavior.
Is the compiler constructing the result directly in the destination record, effectively reusing its existing storage? If so, is this an intentional optimization, perhaps related to copy elision, or something else entirely?
What concerns me is the apparent discrepancy between my understanding of the documentation and the compiler's behavior in this use case. Such discrepancies can lead to subtle, hard-to-find runtime bugs.
Examining the two issues together, I suspect they share the same underlying cause: compiler elision when assigning a record-returning expression to an existing variable. In this case, the variable is sequence; in the previous, it was res.
Based on these two related issues, my recommendation is to be defensive when working with the class operator family of methods. Explicitly establish the required state of Result, rather than assuming it has been initialized to its default values.
For reference, I'm using Delphi 13.2 with the Win32 compiler.