Bug 8098 – Inner class method can modify outer's members regardless of constancy

Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2012-05-15T07:30:00Z
Last change time
2012-05-24T22:38:56Z
Keywords
accepts-invalid, pull
Assigned to
nobody
Creator
smjg
Blocks
2573

Comments

Comment #0 by smjg — 2012-05-15T07:30:06Z
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).
Comment #2 by k.hara.pg — 2012-05-24T08:20:46Z
Comment #3 by github-bugzilla — 2012-05-24T21:13:49Z
Commits pushed to master at https://github.com/D-Programming-Language/dmd https://github.com/D-Programming-Language/dmd/commit/de20f7f9e50c468fe7758604058d0af6bc7f36aa fix Issue 8098 - Inner class method can modify outer's members regardless of constancy https://github.com/D-Programming-Language/dmd/commit/db915a16aba1db00a5ea59f96ad0b0deea7152b5 Merge pull request #964 from 9rnsr/fix8098 Issue 8098 - Inner class method can modify outer's members regardless of constancy