Scope storage class

Sergey Gromov snake.scaly at gmail.com
Thu Dec 4 07:26:42 PST 2008


Mon, 1 Dec 2008 14:10:27 -0500, Steven Schveighoffer wrote:

> "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?

It compiles.

> If it does, then the benefit of having 
> scope delegates is just a hint to the compiler that "I know what I'm doing".

Yes, seems like for now it's just a hint.  No checking is done.

The problem is, the declaration:

  scope var = ...;

means something completely different from

  void foo(scope void delegate() dg);
  foo(...);

The former defines a scoped instance of a class.  Ideally it should fail
if used with any non-class type because it makes no sense with
non-classes.

The latter defines a delegate in a non-escaping context.  Currently such
definition is possible only as a parameter to a function call.

If delegate is defined in a non-escaping context, it gets a stack
closure.  If it is defined as a scoped instance of a class... well, it
makes no sense, so the scope is ignored and the delegate is created as
usual, with a heap-allocated closure.


More information about the Digitalmars-d-announce mailing list