Search code examples
delphidebuggingfor-loopempty-list

Why does the debugger step through a destructor in a for-in loop?


In Delphi XE7 (I use RAD Studio), I try to debug a code inside a package. I'm in trouble with a strange situation that I cannot explain. For example, I have a function similar to the one below (NOTE I know, this function does nothing intelligent, please don't correct it because I don't use it in the real world. It's just a dummy function to illustrate the issue I face.)

procedure TMyClass.DemoFunc();
var
    pTest:     TObjectList<TObject>;
    pProperty: TObject;
begin
    pTest := TObjectList<TObject>.Create;

    for pProperty in pTest do
        pProperty.ToString;

    pTest.Free;
end;

When I debug the above code, I notice that the debugger enters on the line

pProperty.ToString;

If I try to trace into the above line, I jump to

destructor TObject.Destroy;

But from my point of view it's completely illogical, because pTest is clearly empty, and so the above line should never be called.

Somebody can explain to me this strange behavior?

NOTE The code I try to debug is inside a Delphi package, but the function is called from a c++ project.

Regards


Solution

  • The TObject being destroyed is the Enumerator that was created implicitly by the compiler for the For-In loop. It is not the "pProperty". If you bring up an Evaluator when the debugger is stopped at the begin of TObject.Destroy and enter "self.classname" you will see that it's a "TList<System.TObject>.TEnumerator".