Getting the const-correctness of Object sorted once and for all

Stewart Gordon smjg_1998 at yahoo.com
Tue May 15 07:31:16 PDT 2012


On 14/05/2012 18:08, Tove wrote:
<snip>
> class Outer
> {
>   int i = 6; // mutable
>
>   class Inner {
>     int y=0;
>
>     int foo() const
>     {
>       // ++y; // fail
>       return ++i; // look ma, mutable const
>     }
>   }
>   Inner inner;
>   this()
>   {
>     inner = new Inner;
>   }
>   alias inner this;
> }

Indeed, you've found a hole in the const system nobody seems to have noticed before!

Inner.foo is const, so from foo's point of view, Inner.outer needs to be.

To expand your example a bit:
----------
import std.stdio;

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)
----------

but nonetheless, it allows i to be modified!

http://d.puremagic.com/issues/show_bug.cgi?id=8098

Stewart.


More information about the Digitalmars-d mailing list