ref is unsafe

monarch_dodra monarchdodra at gmail.com
Sun Dec 30 02:04:35 PST 2012


On Sunday, 30 December 2012 at 09:18:30 UTC, Jonathan M Davis 
wrote:
> On Sunday, December 30, 2012 10:04:01 Daniel Kozak wrote:
>> IMHO, try to return ref to local variable should be error, and
>> such a code shouldn't be compilable
>
> You can disallow that in the easy case of
>
> ref int boo(int i)
> {
>     return i;
> }
>
> and in fact, that's already illegal. The problem is the wrapper 
> function.
> You'd also have to disallow functions from returning ref 
> parameters by ref.
> Otherwise,
>
> ref int foo(ref int i)
> {
>     return i;
> }
>
> ref int baz(int i)
> {
>     return foo(i);
> }
>
> continues to cause problems. And making it illegal to return 
> ref parameters by
> ref would be a serious problem for wrapper ranges, because they 
> do that sort
> of thing all the time with front. So, that's not really going 
> to work.
>
> - Jonathan M Davis

Wouldn't it be enough to disallow functions that both take and 
return by ref? There would still be some limitations, but at 
least:

//----
@property ref T front(T)(T[] a);
//----
Would still be @safe.

It seams the only code that is unsafe always boils down to taking 
an argument by ref and returning it by ref...

At best, we'd (try) to only make that illegal (when we can), or 
(seeing things the other (safer) way around), only allow 
returning by ref, if the compiler is able to prove it is not also 
an input by ref?


More information about the Digitalmars-d mailing list