Scope storage class

Steven Schveighoffer schveiguy at yahoo.com
Mon Dec 1 11:10:27 PST 2008


"Walter Bright" wrote
> Steven Schveighoffer wrote:
>> "Walter Bright" wrote
>>> Jarrett Billingsley wrote:
>>>> So my suspicion is correct, then?  That is:
>>>>
>>>> scope int delegate() b;
>>>> b = { ... };
>>>>
>>>> Will allocate on the heap?
>>> Yes. The scope for delegates takes effect as a parameter storage class, 
>>> not a local variable storage class. The reason is because it is the 
>>> called function that decides what it's going to do with the delegate.
>>
>> Why?  It would be useful to allow local scope delegates.
>>
>> The compiler can just forbid passing the delegate to a function which 
>> does not declare its parameter as scope.  I assume the compiler knows a 
>> variable is scope since it must prevent escape of the delegate, no?  So 
>> just use that information.  I thought that was the point of all this...
>
> In order to make that work, the compiler would have to do full escape 
> analysis, which is a lot of work to implement.

Maybe I've misunderstood the point of declaring a delegate parameter scope.

Take the following example:

void delegate(int) global_dg;

void foo(void delegate(int) dg)
{
   global_dg = dg;
}

void foo2(scope void delegate(int) dg)
{
   dg(5);
}

void bar(scope void delegate(int) dg)
{
   foo(dg); // should this compile?
   foo2(dg); // should this compile?
}

void baz()
{
   int y;
   void dg(int x) { y += x; }
   bar(&dg);
}

Should bar's call to foo compile?  If it does, then the benefit of having 
scope delegates is just a hint to the compiler that "I know what I'm doing".

If it fails to compile the call to foo, what about the call to foo2?  If 
that fails to compile, then this is a common convention (forwarding a 
delegate) that will cause lots of problems in existing correct code.  If the 
call to foo2 should work, I don't see the difference between the above 
example and this:

void baz2()
{
   int y;
   void dg(int x) { y += x; }
   scope void delegate(int) dg2 = &dg;
   bar(dg2);
}

That is, if you can tell that a delegate is scope or not scope when it's 
being passed to another function, then why can't the compiler use that 
information when the delegate is assigned to another scope delegate?  No 
full escape analysis is needed.

-Steve 




More information about the Digitalmars-d-announce mailing list