How do "pure" member functions work?

Sean Eskapp eatingstaples at gmail.com
Sat Aug 20 09:53:51 PDT 2011


== Quote from Timon Gehr (timon.gehr at gmx.ch)'s article
> On 08/20/2011 06:24 PM, Sean Eskapp wrote:
> > == Quote from David Nadlinger (see at klickverbot.at)'s article
> >> On 8/20/11 5:13 PM, Sean Eskapp wrote:
> >>> Does marking a member function as pure mean that it will return the same
> >>> result given the same parameters, or that it will give the same result, given
> >>> the same parameters and given the same class/struct members?
> >> The second one, the implicit this parameter is just considered a normal
> >> argument as far as purity is concerned.
> >> David
> >
> > Wait, references and pointers are now valid for pure function arguments?
> There are different forms of pure functions:
> weakly pure:
> no mutable globals are read or written. the function may however change
> its arguments. weakly pure functions are useful mainly for the
> implementation of functions with stronger purity guarantees.
> const pure/strongly pure:
> All function arguments are values or const/immutable.
>  From the type signature of a function, you can always tell which form
> of pure function it is:
> int foo(ref int, int) pure; // weakly pure, could change first argument
> int bar(const(int)*, int) pure; // const pure
> int qux(immutable(int)*, int) pure; // strongly pure
> Weakly pure member functions can therefore change the other members:
> struct S{
>      int x;
>      int foo() pure; // weakly pure, could change x
>      int bar() pure const; // const pure, cannot change x
>      int qux() pure immutable; // strongly pure, only works with
> immutable instances
> }
> The rationale of this:
> Consider
> int baz(int x) pure{
>      S s=S(x);
>      S.foo();
>      return s;
> }
> This is clearly strongly pure code. If we had no weakly pure, this could
> not be written in that way.

Oh, I see, thanks! This isn't documented in the function documentation!


More information about the Digitalmars-d-learn mailing list