Why are scope variables being deprecated?

Piotr Szturmaj bncrbme at jadamspam.pl
Wed Oct 10 17:30:50 PDT 2012


Jonathan M Davis wrote:
> On Thursday, October 11, 2012 01:24:40 Piotr Szturmaj wrote:
>> Could you give me an example of preventing closure allocation? I think I
>> knew one but I don't remember now...
>
> Any time that a delegate parameter is marked as scope, the compiler will skip
> allocating a closure. Otherwise, it has to copy the stack from the caller onto
> the heap to create a closure so that the delegate will continue to work once
> the caller has completed (e.g. if the delegate were saved for a callback and
> then called way later in the program). Otherwise, it would refer to an invalid
> stack and really nasty things would happen when the delegate was called later.
 >
> By marking the delegate as scope, you're telling the compiler that it will not
> escape the function that it's being passed to, so the compiler then knows that
> the stack that it refers to will be valid for the duration of that delegate's
> existence, so it knows that a closure is not required, so it doesn't allocate
> it, gaining you efficiency.

Thanks, that's clear now, but I found a bug:

__gshared void delegate() global;

void dgtest(scope void delegate() dg)
{
     global = dg; // compiles
}

void dguse()
{
     int i;
     dgtest({ writeln(i++); });
}

I guess it's a known one.


More information about the Digitalmars-d-learn mailing list