Purity with references and pointers

Jonathan M Davis jmdavisProg at gmx.com
Sat Sep 18 18:16:31 PDT 2010


On Saturday 18 September 2010 17:33:21 Simen kjaeraas wrote:
> Jonathan M Davis <jmdavisProg at gmx.com> wrote:
> > If a pure function takes a reference/pointer, does that state that the
> > result of
> > the function will be the same on two calls to it if the
> > reference/pointer points
> > to the same data in both cases or if the data itself is unchanged?
> > 
> > If it's a matter of pointing to the same data, then that could be
> > horribly
> > broken. That would mean that as long as I pased in the same reference,
> > the
> > compiler could cache the result but that the actual result of the
> > function could
> > have and should have been different for each call because the object
> > pointed to
> > was altered.
> 
> "[A] pure function [...] has parameters that are all immutable or are
> implicitly convertible to immutable" [1]
> 
> This implies that any pointer passed to a pure function must point
> to immutable data. This means the pointed-to data can not change
> between two calls to the function.
> 
> 
> [1]: http://digitalmars.com/d/2.0/function.html#pure-functions

Except that since when is anything implictly convertable to immutable? 
Implicitly converted to const, yes. That happens often enough, but immutable? 
And you definitely don't have to use immutable references with pure functions.

I have gotten some const-related errors when using pure on member functions, so 
I get the impression that using pure on a member function implicitly makes it 
const, but I'm not sure if that's enough. Maybe pure implicitly make all pointer 
and reference parameters const, and if function purity is only ever used to 
optimize within an expression rather than across multiple statements, then that 
would be enough. But if it tried to optimized multiple pure function calls 
within a function, and there were statements in between which altered one of the 
objects passed into the pure function, then such an optimization wouldn't 
necessarily be valid.

It sounds to me like the docs need updating. I don't think that *anything* is 
implicitly convertable to immutable. const yes, but not immutable

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list