Safe to cast to immutable and return?

Steven Schveighoffer schveiguy at yahoo.com
Thu Jul 5 12:34:52 UTC 2018


On 7/5/18 7:15 AM, 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;
> }

As in @safe? no. But it's safe in the fact that you aren't escaping any 
mutable references as immutable. However, casting is dangerous. It 
disables any checks about const safety that the compiler may do. If 
something happens to A where it all of a sudden gains a mutable 
reference, and the reference is to global data or has other references:

class A { int *x; }

int globalx;
immutable(A) getA()
{
    A a = new A;
    a.x = &globalx;
    return cast(immutable A)a;
}

Now it's not safe, and the compiler won't tell you.

> 
> What if A is replaced with A[] or A[int]?

A[] should work very similarly to A

A[int] I think will work, I don't think it stores any type info inside 
the AA.

The rule is that if you *know* there are no other references to a 
mutable piece of data, it's OK to cast to immutable.

> 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?

See vit's response, he covers it pretty well.

-Steve


More information about the Digitalmars-d-learn mailing list