I guess other persons have already suggested something like this.
Here there is a "lazy immutable" instance member x, that can be
only in two states: not initialized, and initialized with an
immutable value.
The type system ensures x is never read before it's written, and
that it's written no more than once (and to do this I presume it
needs flow analysis).
The point of this idea is to make the bar() method const despite
the x instance attribute is computed only if it's needed. This is
useful is spam() requires significant computations, but x is not
always needed. So it allows bar() to be "logically const" in a
verified correct way.
int spam() pure nothrow @safe @nogc {
// Lot of computations here.
return 0;
}
struct Foo {
private lazy immutable int x;
static assert (this.x.sizeof == 8);
int bar() const pure nothrow @safe @nogc {
if (this.x.isNull) {
this.x = spam();
}
return this.x;
}
}
void main() {}
Bye,
bearophile