Below is a SSCCE based on an example in the Anonymous Methods section of Part 1
of Chris Rolliston's excellent Delphi XE2 Foundations book, about the idea of variable
capture (any errors in it are entirely down to me).
It works exactly as I'd expect, logging 666, 667, 668, 669 on successive clicks of the
BtnInvoke button. In particular it nicely illustrates how the captured version of the
local variable I persists long after btnSetUpClick exits.
So far so good. The problem I'm asking about isn't with this code per se but with
what's said in Allen Bauer's blog here:
http://blogs.embarcadero.com/abauer/2008/10/15/38876
Now, I know better than to argue with the boss, so I am sure I'm missing the point
of the distinction he draws between variable capture and value capture. To my simple way
of looking at it, my CR-based example captures the value of I by capturing I as a variable.
So, my question is, what is the distinction Mr Bauer is trying to draw, exactly?
(Btw, despite watching the Delphi section of SO daily for 9+ months, I'm still not entirely
clear if this q is on-topic. If not, my apologies and I'll take it down.)
type
TAnonProc = reference to procedure;
var
P1,
P2 : TAnonProc;
procedure TForm2.Log(Msg : String);
begin
Memo1.Lines.Add(Msg);
end;
procedure TForm2.btnSetUpClick(Sender: TObject);
var
I : Integer;
begin
I := 41;
P1 := procedure
begin
Inc(I);
Log(IntToStr(I));
end;
I := 665;
P2 := procedure
begin
Inc(I);
Log(IntToStr(I));
end;
end;
procedure TForm2.btnInvokeClick(Sender: TObject);
begin
Assert(Assigned(P1));
Assert(Assigned(P2));
P1;
P2;
end;
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…