Suggestion: "new delegate" - delegates useable outside of the nesting function scope

Burton Radons burton-radons at smocky.com
Fri Jun 2 18:57:50 PDT 2006


Walter Bright wrote:

> Burton Radons wrote:
> 
>> I use delegates a lot but the fact that they can only live until the 
>> end of the nesting function scope means I need to use classes in many 
>> cases, which is a lot more typing (and fluff telling the autodoc that 
>> it's not part of the public API, and other problems) when it could be 
>> easily fixed. The syntax change would be very simple:
>>
>>     dispatcher.add (new delegate void (Event event) { ... });
>>
>> And the effect would be simple as well: duplicate the calling 
>> context's stack to the extent that the delegate can see it and use the 
>> duplicated pointer as the "this" pointer; otherwise it's a regular 
>> nested delegate. Five minutes work max, very topical changes, explicit 
>> allocation, big benefits. Is good!
> 
> 
> Unfortunately, it's quite a bit more work than that. You have to copy 
> all the frames of the lexically enclosing functions, too. Then you have 
> the issue of updates to the framed variable copies not being reflected 
> in the stack variables. Then there's the problem of things like:
> 
>   int x;
>   int* px = &x;

Good points (I forgot about multiple nesting - did I ever compliment you 
for putting that in with the first release containing nested functions? 
- but you need to chain anyway so the logic must already be in there to 
piggyback onto), it is more work but compare it to the work required 
when it's omitted. I have done terrible things, committed sins against 
good engineering just because my nesting scope exits, and while it 
hasn't had a cooling effect on me, I'm sure there have been other people 
who have resorted to inferior Java class-inheritance techniques just to 
get around this problem. I have to admit I've done it once or twice. I 
was young and naive!

Frozen variables are, of course, a feature, not a bug, and one the user 
would opt into by using the "new" variant. We discussed this in 2003. 
;-) Anyway in three years and four months I haven't depended on the 
nesting scope's variables varying once, and while I haven't really 
wanted them to be frozen either, I've used it a few times in languages 
which freeze the nesting scopes (like Python).

The only really good argument against this originally, in my opinion, 
was that it was a hidden allocation, but it's explicit like this.



More information about the Digitalmars-d mailing list