@nogc inconsistent for array comparison depending on mutability of elements

Nick Treleaven via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Apr 8 02:56:41 PDT 2016


On Friday, 8 April 2016 at 03:14:40 UTC, Xinok wrote:
> 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.

So @nogc is enforced by the optimizer?

If the comparison with b shouldn't be allowed, I suggest we add 
opEquals to std.range.only. This removes a need to import 
std.algorithm.equal and reduces bracket nesting:

assert(b == only(1, 2));


More information about the Digitalmars-d-learn mailing list