Safe cast away from immutable

Iakh via Digitalmars-d digitalmars-d at puremagic.com
Tue Feb 9 10:40:46 PST 2016


On Tuesday, 9 February 2016 at 16:32:07 UTC, Steven Schveighoffer 
wrote:
> I think the rules at the moment are that the compiler allows 
> implicit conversion if the return value could not have come 
> from any of the parameters. But what it may not consider is if 
> the parameters could be return values themselves via a 
> reference!

AFAIK it just traverse members and search for exactly match with 
return
type. Even more there is different checks for "pure" and "unique 
owned
result".

import std.stdio;

int[] f(void[] a) @safe pure
{
     return cast(int[])a;
}

void main() @safe
{
     int[] a = new int[4];

     immutable b = a.f();
     writeln(b);
     a[0] = 1;
     writeln(b);
}

This works until you change void[] to int[].
And error message is about casting to immutable not about purity.

This is terribly because if there is a code:

int[] f(SophisticatedClass a){...}
immutable a = f(new SophisticatedClass);

that was working last 100 years but then somebody adds member
of type int[] into SophisticatedClass.field.field.field
You take sort of this:
Error: cannot implicitly convert expression (f(a)) of type int[] 
to immutable(int[])

It's hard to prove that result is unique. So maybe don't try to 
do?


More information about the Digitalmars-d mailing list