On Friday, 8 April 2016 at 01:36:18 UTC, rcorre wrote:
@nogc unittest {
    int[2] a = [1, 2];
    assert(a == [1, 2]); // OK

    immutable(int)[2] b = [1, 2];
assert(b == [1, 2]); // fail: array literal may cause allocation
}

Is there any logic behind allowing the comparison with `a` but not `b`, or is this a compiler bug?

Semantically, array literals are always allocated on the heap. In this case, the optimizer can obviously place the array on the stack or even make it static/global. However, it would be in poor design to rely on the optimizer to satisfy @nogc. It comes down to portability; if the code compiles successfully with one compiler, then it should compile successfully in any other compiler.

Also, the way that compilers are typically built is that semantic analysis is done in the frontend and optimization is done in the backend. Trying to build a bridge between these two would be incredibly difficult and make implementing the compiler much more complex with little gain.

Reply via email to