Re: Pure Factory Functions 💔 `inout`

ag0aep6g anonymous at example.com
Tue Feb 21 14:31:37 UTC 2023


On 21.02.23 14:58, Quirin Schroll wrote:
> ```d
> @safe:
> 
> int* foo(double[] xs) pure
> {
>      if (xs.length >= 2)
>          xs[0] = xs[$ - 1];
>      return new int;
> }
> 
> void main()
> {
>      double[] xs = [];
>      immutable a = foo(xs);
> }
> ```

That right there is nothing but a safety hole. D allows casting from 
`double[]` to `int[]`, so the compiler cannot assume uniqueness in that 
case.

More explosive test case:

----
@safe:

int[] foo(ubyte[] bytes) @safe pure
{
     return cast(int[]) bytes; /* the language very much allows this */
}

void main()
{
     ubyte[] bytes = [42, 0, 0, 0];
     immutable ints = foo(bytes);
     assert(ints[0] == 42); /* passes */
     bytes[0] = 13;
     assert(ints[0] == 42); /* fails; immutable int changed value */
}
----


More information about the Digitalmars-d mailing list