Opportunities for D

Artur Skawina via Digitalmars-d digitalmars-d at puremagic.com
Wed Jul 9 16:27:45 PDT 2014


On 07/10/14 00:16, H. S. Teoh via Digitalmars-d wrote:
> On Wed, Jul 09, 2014 at 11:33:09PM +0200, Johannes Pfau via Digitalmars-d wrote:
> [...]
>> 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);
>> }
> 
> Unfortunately, it seems that this is not enforced by the compiler at
> all. 

Yes, scope is not enforced at all.

Also:

void main()
{
    int a;
    auto callback = {a = 42;};  // heap alloc
    scope callback = {a = 42;}; // stack (ie normal) alloc
    testA(callback); 
    testB(callback);
}

Then there are lazy args, which are basically scope delegates,
but with no way to turn off 'scope' and no escape protection.


Trying to tack 'borrowed' on 'ref' is not a good idea. (would
require new restrictions, hence not backwards compatible; it can't
be a @safe-only thing, `borrowed` affects lifetimes etc)

artur 


More information about the Digitalmars-d mailing list