Uh... destructors?

Jonathan M Davis jmdavisProg at gmx.com
Tue Feb 22 13:27:36 PST 2011


On Tuesday, February 22, 2011 12:48:42 %u wrote:
> > D pure functions are significantly different than this definition
> 
> (as of recent times, when weak-pure was added).
> 
> > Essentially, a pure function cannot access global variables.
> 
> However, it can access variables referred to via a member of the
> object instance.
> 
> > i.e. this is a valid pure function:
> class C
> {
>    int x;
>    pure void foo() { x++; }
> }
> 
> I... did not know that. But even in that case, pure wouldn't make much
> sense, because doing anything like freeing memory or closing a file
> handle affects global variables (whether directly in the runtime or
> indirectly in the OS)... right?

Except that newing something up is pure. pure is used in D to allow for 
optimizations. That and being able to say that a function doesn't access globals 
are pretty much the only real reasons for its existence, I think. A pure 
function does not allow any access to mutable global variables (and it may or 
may not presently allow access to immutable global variables - I don't remember 
- but it could). A strongly pure function (a pure function whose parameters are 
all immutable or implicitly convertible to immutable) can have multiple calls to 
it with the same values optimized out. A weakly pure function (a pure function 
which is not strongly pure) can't be optimized out, but it _can_ be called from 
a strongly pure function - unlike non-pure functions.

Constructors and destructors are funny cases, since they mess with memory, but 
you have to be able to make them pure (or at least you have to be able to make 
constructors pure) or you can't allocate anything in a pure function You can't 
optimize them out, but they _are_ designed such that you can call them from pure 
functions if they're pure. So, it would really only matter whether a destructor 
were pure if you called it from a pure function, and you don't normally call 
destructors. So, I don't think that there's necessarily anything wrong with 
marking a destructor as pure, but I'm not sure that there's necessarily much 
point to it either.

- Jonathan M Davis


More information about the Digitalmars-d mailing list