ref is unsafe

Timon Gehr timon.gehr at gmx.ch
Thu Jan 3 13:08:36 PST 2013


On 01/03/2013 01:52 PM, Jason House wrote:
> On Thursday, 3 January 2013 at 05:56:27 UTC, Timon Gehr wrote:
>> On 01/03/2013 12:48 AM, Jason House wrote:
>>> ...
>>>
>>>>
>>>> ref int bar()
>>>> {
>>>>    int i = 7;
>>>>    return foo(i);
>>>> }
>>>
>>> If @safe, this code will not compile.
>>> Error: foo may return a local stack variable
>>> Since "i" is a local variable, "foo(i)" might return it.
>>>
>>>
>>>>
>>>> ref int baz(int i)
>>>> {
>>>>    return foo(i);
>>>> }
>>>
>>> This function is fine. "i" is an input argument so "foo(i)" is
>>> considered to be equivalent to an input argument.
>>>
>>
>> Those two cases are pretty much the same.
>
> If what I suggest is done, they must be differentiated. If you replace
> "return foo(i)" with "return i", the compiler will already issue an
> error for the local variable case.

Obviously _both_ examples result in memory corruption. i is not a ref 
parameter.


More information about the Digitalmars-d mailing list