class Outer {
int i = 6;
class Inner {
int y=0;
int foo() const {
pragma(msg, "this.outer: " ~ typeof(this.outer).stringof);
pragma(msg, "i: " ~ typeof(i).stringof);
return ++i;
}
}
Inner inner;
this() {
inner = new Inner;
}
}
void main() {
const(Outer) x = new Outer;
pragma(msg, "x: " ~ typeof(x).stringof);
pragma(msg, "x.inner: " ~ typeof(x.inner).stringof);
x.inner.foo();
writeln(x.i);
}
----------
C:\Users\Stewart\Documents\Programming\D\Tests>dmd inner_const.d
this.outer: const(Outer)
i: const(int)
x: const(Outer)
x.inner: const(Inner)
C:\Users\Stewart\Documents\Programming\D\Tests>inner_const
7
----------
(DMD 2.059 Win32)
x is a const reference. By transitivity, x.inner is. So far, so good.
Outer.Inner.foo is a const method. The call fails if it isn't. So far, so good.
From foo's point of view, this.outer and i are reported as const. So far, so good.
But despite i being const, it allows it to be modified!
Changing the declaration of x to
const(Outer) x = new const(Outer);
const(Outer) x = new immutable(Outer);
immutable(Outer) x = new immutable(Outer);
makes no difference to the bug.
Comment #1 by smjg — 2012-05-15T07:47:50Z
An inner class holds a hidden member that is a reference to the object of the outer class to which it belongs. By transitivity, if inner is const or immutable, then outer must be likewise from inner's point of view.
This implies that an immutable inner can only belong to an immutable outer, and a const inner can belong to a mutable, const or immutable outer, but inner will always view the outer as const.
At the moment there doesn't seem to be a way to explicitly set the constancy of Inner.outer. But if there were, it would enable a mutable inner to belong to an outer of any constancy while ensuring const-safety (though the outer class might not be able to hold a reference to the inner object).