dip1000 and preview in combine to cause extra safety errors

Walter Bright newshound2 at digitalmars.com
Mon Jun 13 23:58:26 UTC 2022


On 6/9/2022 7:46 AM, Dennis wrote:
> A pointer to a local is guaranteed to be a dangling pointer when you return it, 
> while a `scope` pointer is not guaranteed to be memory with limited lifetime 
> when you return it. `scope` is only a conservative compile-time approximation of 
> what's actually happening, which makes it susceptible to false positives:
> 
> ```D
> int* f(int x) @safe {
>      int* p = &x; // p is inferred scope here
>      p = new int; // p is no longer pointing to stack memory
>      return p;    // Error: scope variable `p` may not be returned
> }
> ```
> This function could be permitted as @system or @trusted code.

I suggest there is little point to permitting it, as good style would expect 
that a different variable be used for each purpose, rather than "recycling" an 
existing variable.

I.e.:


```D
int* f(int x) @safe {
     int* p = &x;
     int* q = new int;
     return q;
}
```


More information about the Digitalmars-d mailing list