Opportunities for D

Johannes Pfau via Digitalmars-d digitalmars-d at puremagic.com
Wed Jul 9 14:33:09 PDT 2014


Am Wed, 9 Jul 2014 13:09:30 -0700
schrieb "H. S. Teoh via Digitalmars-d" <digitalmars-d at puremagic.com>:

> Speaking
> > >of which, what *is* the current extent of the implementation of
> > >'scope'? I assume it isn't just a no-op, since I see it applied to
> > >delegate parameters every now and then?  
> > 
> > Yes, yes, yes, ... these are questions that all need investigation
> > and answering.  
> 
> Surely the last question doesn't need *investigation* per se?? Or do
> we really have no idea whatsoever as to what 'scope' currently does in
> dmdfe at all?

So this was not a rhetoric question?
For delegates scope can prevent closure heap allocation. For all other
types it does nothing. Example:

import std.stdio;

void testA(void delegate() cb)
{
    cb();
}
void testB(scope void delegate() cb)
{
    cb();
}

void main()
{
    int a;
    void callback() {a = 42;}
//Callback accesses a, testA might store a reference to callback
//->a might be accessible after this main function returns
//->can't keep it on the stack. Allocate a on the heap
    testA(&callback); 

//Callback accesses a, but testB does not store a reference
//as it tells us by using scope
//So as soon as testB returns, there's no reference to a floating
//around and we can allocate a on the stack.
//(Of course as long as we call testA in this function, a is always on
// the heap. but if we only call testB it can be on the stack)
    testB(&callback);
}


More information about the Digitalmars-d mailing list