-dip1000 and non-scope variables

Paul Backus snarwin at gmail.com
Thu Feb 18 15:22:06 UTC 2021

On Thursday, 18 February 2021 at 14:33:19 UTC, Dukc wrote:
> On Thursday, 18 February 2021 at 10:05:52 UTC, RazvanN wrote::
>> class MinPointerRecorder
>> {
>>     int* minPrice;
>>     void update(ref int price) @safe
>>     {
>>         minPrice = &price; /* Should not compile. */
>>     }
>> }
>> [snip]
>> Does anyone know what exactly is the intended behavior? 
>> Unfortunately both the spec and the DIP [2] do not explicitly 
>> mention this cases.
> That member function itself can compile, no problem. But 
> -dip1000 should prevent calling it with a local argument:

This was my understanding as well, based on paragraph 4 of the 
spec's section on "Return Ref Parameters" [1]:

> If the function returns void, and the first parameter is ref or 
> out, then all subsequent return ref parameters are considered 
> as being assigned to the first parameter for lifetime checking. 
> The this reference parameter to a struct non-static member 
> function is considered the first parameter.

(I assume "struct" here is supposed to be "struct or class".)

But if you try it with a struct instead of a class, the compiler 
*does* flag the assignment as invalid, even with an explicit 
`return` annotation:

struct MinPointerRecorder
     int* minPrice;
     void update(return ref int price) @safe
         minPrice = &price;
         // Error: address of variable `price` assigned to `this` 
with longer lifetime

On the other hand, if you change the `ref` to a `scope` pointer, 
it compiles again:

struct MinPointerRecorder
     int* minPrice;
     void update(return scope int* price) @safe
         minPrice = price; // Ok

So, I'm not sure what the correct answer here is.

[1] https://dlang.org/spec/function.html#return-ref-parameters

More information about the Digitalmars-d mailing list