Jump to content
Sign in to follow this  
Lars Fosdal

Pitfalls of Anonymous methods and capture

Recommended Posts

5 hours ago, Lars Fosdal said:

Close, its a Self-Contained Compilable Example, sometimes also called a SSCCE, i.e. a Short SCCE. 

 

I'll rewrite the article for better readability. 

 

Hmmm... I knew I had read something like it before, but couldn't find it anywhere (in a meaning that made sense). The missing S did it.

Share this post


Link to post
On 2/8/2019 at 2:19 PM, Lars Fosdal said:

Code that looks correct, and appear to compile alright, but which doesn't execute well.
Can you spot the error? See my blog post for a link to a SCCE.


var
  Handler: THandlerClass;
  hType: THandlers;
begin
  Broker.Clear;
  for hType in [foo, bar]
  do begin
    case hType of
      foo: Handler := TFoo.Create;
      bar: Handler := TBar.Create;
    end;
    Broker.AddHandler(Handler.OnHandle);
  end;
end;


https://larsfosdal.blog/2019/02/08/delphi-pitfalls-of-anonymous-methods-and-capture/

FWIW, this is similar to the call-by-name problem (Jensen's device) in Algol 60.

 

And similar problems can happen if people do:

for I := 1 to 10 do
begin
  MyRecord.Int := I;
  MyPlainTList.Add(@MyRecord);
end;

The entire plain TList is now filled with pointers to the same record, and that contains the value 10. <g>

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×