ref is unsafe

Rob T rob at ucora.com
Thu Jan 3 15:58:45 PST 2013


OK, I understand what you mean by "scope" and how that can be 
used to prevent leaking a local ref out.

Don't forget to consider this kind of scenario, which has no ref 
arguments to consider

struct X
{
    int _i;
    ref int f()
    {
       return _i;
    }
}

ref int F()
{

    X x;
    return x.f();
}

int main()
{
     // example uses that currently compile
     F = 1000;
     writeln(F());
}

Is this valid? Does local x remain defined up until the function 
call terminates completely, ie until after the reference is no 
longer valid?

I can also mark everything as @safe and it will compile, and also 
scope x

@safe ref int F()
{

    scope X x;
    return x.f();

    // this compiles too

    return x._i;

}

--rt


More information about the Digitalmars-d mailing list