I have a struct with a private member that is only ever accessed through a single property method - even from within the struct. As this property fills the value on the first access, it cannot be immutable, and as such, none of the many methods accessing this property can be immutable methods.

This is according to specification, but I thought that since the single write to the property is done at one, and only one, access point, that it would be safe?

I could fill this value in the constructor, but it's a bit slow, so I'd rather do it only if needed.

And is there any potential performance optimizations done by the compiler, or is it "only" for safety? Is there a way to hack around this, and more importantly, is it safe to do so, or will I open Pandora's box?


Small example:

int len(const char[] c) {
    return c.length;
}

struct S {
    private immutable(char)[] _v;
    @property immutable(char[]) v() { // Cannot be immutable method
        if(!_v)
            _v = "init"; /* or from external function */
        return _v;
    }

    @property int a() { // and so this cannot be immutable method
return len(v); /* notice the property function v that might modify _v */
    }
}

void main() {
    S s;
    s.a;
}

Reply via email to