Uh... destructors?
Michel Fortin
michel.fortin at michelf.com
Wed Feb 23 09:14:05 PST 2011
On 2011-02-23 11:45:48 -0500, Andrei Alexandrescu
<SeeWebsiteForEmail at erdani.org> said:
> On 2/23/11 9:57 AM, Steven Schveighoffer wrote:
>> On Wed, 23 Feb 2011 10:46:43 -0500, Andrei Alexandrescu
>> <SeeWebsiteForEmail at erdani.org> wrote:
>>
>>> At a level it's clear to me that a function cannot be at the same time
>>> pure and unsafe. For example:
>>>
>>> pure void foo(int *x) { free(x); (*x)++; }
>>>
>>> This function essentially breaks any guarantee for the entire program,
>>> so it would be quite difficult to claim it's pure.
>>
>> I thought @safe was orthogonal to pure? If this isn't the case, then
>> yes, free must be disallowed. But then malloc must also be, and any
>> construct which manages its own memory via malloc/free.
>
> malloc can be reasonably made pure. It would be a mistake to see malloc
> and free as two symmetrical parts of a whole. The truth of the matter
> is that allocating is fine, deallocating is problematic.
Deallocating is problematic if after deallocation you continue to keep
references to the deallocated memory. Generally speaking, it's unsafe
to keep references to deallocated memory; whether you're in a pure
function or not does not change that.
There's no question that 'free' should be a @system function because if
used incorrectly your program will behave erratically. But this has
nothing to do with purity.
There's no question that malloc/free manipulates the global state. The
problem to purity I see in that is that the memory address returned by
malloc will be different each time. We've decided that allocating
memory with the 'new' keyword was fine, so I don't see any harm in
allowing 'malloc' too (as long as you can make sure the compiler won't
fuse two malloc calls in one if they have the same argument). As for
free, theoretically you should never call it twice with the same
argument, so I don't see any harm in making it pure.
If you want your pure function to also be safe, it's easy to make it @safe.
--
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/
More information about the Digitalmars-d
mailing list