On Thursday, 5 July 2018 at 11:15:03 UTC, Timoses wrote:
Is this safe?

class A {}
immutable(A) getA()
{
    A a;
    // .. do stuff with a
    // not leaking a to any functions

    // is this safe????
    return cast(immutable A)a;
}

What if A is replaced with A[] or A[int]?
If it's not safe, what would be the proper way to return an immutable instance from a function which needs to make adjustments to the instance before returning it as immutable?

Try pure functions:

class A {}
A getA()pure @safe //pure whitout mutable parameters guarantees that function doesn't leak data.
{
     A a;
     // .. do stuff with a
     // not leaking a to any functions

     // is this safe????
     return a;
}
A getA2(A x)pure @safe  //pure with mutable param
{
     A a;
     // .. do stuff with a
     // not leaking a to any functions

     // is this safe????
     return a;
}

void test()@safe{
    immutable(A) a1 = getA();        //ok
    immutable(A) a2 = getA2(null);   //ok
    immutable(A) a3 = getA2(new A);  //ok
    immutable(A) a4 = getA2(a3);    //error in theory can leak




}

Reply via email to