Should pure functions be prevented from reading changeable immutable static variables?
Tomek Sowiński
just at ask.me
Sat Nov 6 13:39:28 PDT 2010
Don napisał:
> Pure functions are allowed to read immutable global variables.
> Currently, this even includes globals which are initialized from inside
> 'static this()'.
> Here's an example of how this can be a problem:
>
> immutable int unstable;
>
> pure int buggy() { return unstable; }
>
> static this() {
> // fails even though buggy is pure
> assert( buggy() == ( ++unstable , buggy() ) );
> }
Interesting. It looks like more of a problem with initialization of immutables,
though. I think we're in need for rules governing access to immutable
globals in static constructors, e.g.
module A;
immutable int immut;
static this() {
foo(immut); // error, reading an uninitialized immutable
immut = 5; // ok, initializing immutable
foo(immut); // ok, reading an initialized immutable
immut = 4; // error, mutating an initialized immutable
}
In the real world outside static this() the approach is healthy -- mutating an
immutable variable is allowed only in a very narrow time-slice just to allow
publishing. The post-init use of the immutable is constrained by the
compiler armed with a const-aware type system. The pre-init time is also
protected because there is no symbol representing an uninitialized
immutable variable others can refer to (it doesn't exist before initialization).
But inside static constructors immutables can be mutated at will, that's
where the problems come from.
--
Tomek
More information about the Digitalmars-d
mailing list