Uh... destructors?
Steven Schveighoffer
schveiguy at yahoo.com
Tue Feb 22 14:25:17 PST 2011
On Tue, 22 Feb 2011 16:34:21 -0500, bearophile <bearophileHUGS at lycos.com>
wrote:
> Steven Schveighoffer:
>
>> Freeing and allocating memory is fair game for pure functions.
>
> Allocating arrays and objects is possible in pure D functions, despite
> the memory pointers they contain (like the ptr of a returned array) are
> different across different calls. This makes those function only
> formally pure and requires care from both the programmer and the
> optimizations done by the compiler, to avoid some bad bugs :-)
>
> Example: the C calloc() function is not considered pure, despite what it
> does is not so far from a pure D function that allocates and returns a
> dynamic array of ubytes:
>
> import core.stdc.stdlib: calloc;
>
> // OK
> pure ubyte* foo1(int n) {
> auto a = new ubyte[n];
> return a.ptr;
> }
>
> // Error: pure function 'foo2' cannot call impure function 'calloc'
> pure ubyte* foo2(int n) {
> return cast(ubyte*)calloc(n, 1);
> }
>
> void main() {}
I would think malloc and friends should be pure, as well as free. They
can easily simply be marked pure, since they are C bindings.
> Regarding freeing memory in pure functions, I am even less sure.
If allocation is pure, freeing should also be pure. You should be allowed
to clean up what you created in a pure function.
To draw a parallel, a GC collect cycle should be "pure", even though it
affects global state. Otherwise, the GC would have to be disabled during
pure functions.
-Steve
More information about the Digitalmars-d
mailing list