On Tuesday, 9 April 2013 at 07:57:37 UTC, Manu wrote:
Are you saying the example above is not actually valid code?

struct Foo {
    int a = 0;
    pure int bar( int n ) { // Weakly pure
        a += n;
        return a;
    }
}

That's not pure. Call it twice with the same args, you'll different
answers. How can that possibly be considered pure in any sense?
And it's useless in terms of optimisation, so why bother at all? What does
it offer?

deadalnix answered but too briefly it seems. I think the reason it's pure is because a struct's member functions are actually a kind of syntax sugar. Foo.bar above is rewritten underneath as something like:

pure int __Foobar(ref Foo __f, int n) {
    __f.a += n;
    return __f.a;
}

Therefore if a were defined outside the struct,

int a = 0;
struct Foo {
    pure int bar( int n ) {
        a += n; // Epic fail
        return a;
    }
}

... it would fail completely, but 'a' is a struct field and so passed by hidden pointer to the member function, which is therefore in essence weakly pure.

Reply via email to