ref is unsafe

Daniel Kozak kozzi11 at gmail.com
Sun Dec 30 01:04:01 PST 2012


On Sunday, 30 December 2012 at 08:38:27 UTC, Jonathan M Davis 
wrote:
> After some recent discussions relating to auto ref and const 
> ref, I have come
> to the conlusion that as it stands, ref is not @safe. It's 
> @system. And I
> think that we need to take a serious look at it to see what we 
> can do to make
> it @safe. The problem is combining code that takes ref 
> parameters with code
> that returns by ref. Take this code for example:
>
> ref int foo(ref int i)
> {
>     return i;
> }
>
> ref int bar()
> {
>     int i = 7;
>     return foo(i);
> }
>
> ref int baz(int i)
> {
>     return foo(i);
> }
>
> void main()
> {
>     auto a = bar();
>     auto b = baz(5);
> }
>
> Both bar and baz return a ref to a local variable which no 
> longer exists. They
> refer to garbage. It's exactly the same problem as in
>

IMHO, try to return ref to local variable should be error, and 
such a code shouldn't be compilable


More information about the Digitalmars-d mailing list