Thursday, 12 September 2013

How can I set an external variable to nil inside a method?

How can I set an external variable to nil inside a method?

I'd like to subclass TThread in order to have a thread class that, when
FreeOnTerminate = True, sets to nil its reference variable. In other
words, I want do do something like this:
TFreeAndNilThread = class(TThread)
private
FReferenceObj: TFreeAndNilThread; //?? // <-- here I'm holding the
reference to myself
protected
procedure Execute;
procedure DoTerminate; override; // <-- here I'll set FReferenceObj to
nil after inherited (only if FreeAndNil = True)
public
constructor Create(CreateSuspended: Boolean; var ReferenceObj);
reintroduce; <-- untyped param like FreeAndNil and
TApplication.CreateForm ??
end;
The consumer code should be like this:
var
MyThread: TFreeAndNilThread;
begin
MyThread := TFreeAndNilThread.Create(True, MyThread);
MyThread.FreeOnTerminate := True;
MyThread.Resume;
end;
...and then I could safely test for Assigned(MyThread).
I see how FreeAndNil manages to set a reference object passed by untyped
param to nil, but it does this locally. In my case I should "save" it to a
class field (FReferenceObj) and make it nil in another place
(DoTerminate).
How can I correctly pass, store and retrieve it? I can think of passing
and storing the address of MyThread instead of MyThread itself, but I hope
there is a more elegant way.
Thank you!

No comments:

Post a Comment