DIP1000: Scoped Pointers (Discussion)

Walter Bright via Digitalmars-d digitalmars-d at puremagic.com
Mon Aug 15 04:52:01 PDT 2016


On 8/15/2016 2:32 AM, Kagamin wrote:
> On Sunday, 14 August 2016 at 20:02:35 UTC, Walter Bright wrote:
>> auto r = range;
>
> You said that if a value (range in this case) is returned by scope, its lifetime
> is restricted to its expression, hence it can't be assigned to a variable,
> because the variable outlives the expression.

A very good question. If the functions parameters are 'return scope', that means 
the returned value has the (smallest) scope if its 'return scope' parameters. If 
there are no 'return scope' parameters, the scope of the return value is limited 
to the expression.

This is why things like this will work:

   scope int* foo(return scope int* p) { return p; }

   int i;
   int* q = foo(&i); // ok

because the compiler knows that the address of i is what is being returned, and 
q has a shorter lifetime than i.

Also:

   scope int* foo(scope int* p) { return p; }

would be an error, and:

   scope int* foo(int* p) { return p; }
   int* q = foo();  // error


More information about the Digitalmars-d mailing list