GC.malloc is pure - wat

ZombineDev via Digitalmars-d digitalmars-d at puremagic.com
Fri Apr 1 00:58:46 PDT 2016


On Friday, 1 April 2016 at 05:00:43 UTC, ag0aep6g wrote:
> On 01.04.2016 00:52, deadalnix wrote:
>> Is it not pure, strong or weak. GC.malloc is pure because the 
>> memory is
>> going to be garbage collected. malloc is not pure as the 
>> memory need to
>> be freed. The state in the allocator is exposed to the program.
>
> How does malloc expose its state and GC.malloc doesn't?
>
> * They have the same signature. Both return pointers (to 
> mutable data).
> * malloc has free, GC.malloc has GC.free. So you can manually 
> free the memory in both cases.
> * You don't have to free memory from malloc. You can let it 
> leak.
>
>> Lie to the compiler and it will punish you for it.
>
> This also happens with functions that have an implementation in 
> source:
>
> ----
> int[] f() pure nothrow {return [0];}
>
> void main()
> {
>     auto a = f();
>     auto b = f();
>     a[0] = 1;
>     b[0] = 2;
>
>     import std.stdio;
>     writeln(a is b); /* should be false */
>     writeln(a[0]); /* should be 1 */
> }
> ----
>
> Prints "true" and "2" when compiled with `dmd -O -release`.
>
> So I don't think that lying to the compiler is the problem here.

The last case is different. It has nothing to do with pure. It is 
about reference-type literals and default field values:

class C { int x; }

struct S
{
     C c = new C;
     int[] arr = [1, 2, 3];
}

S s1, s2;

assert (s1.arr is s2.arr);
assert (s1.c is s2.c);

immutable S s3;

s1.arr[0] = 42;
s1.c.x = 24;
assert (s2.arr[0] == 42);
assert (s3.arr[0] == 42);
assert (s2.c.x == 24);
assert (s3.c.x == 24);


More information about the Digitalmars-d mailing list