rebind of const class variables

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jan 20 01:48:32 PST 2015


On Tuesday, January 20, 2015 09:29:45 qqiang via Digitalmars-d-learn wrote:
> I am writing a tree data structure, and I have the following code:
>
> ```D
> final class Node {
>      private {
>   int val_;
>   Node parent_;
>   Node left_;
>   Node right_;
>      }
>
>      @property
>      const(Node) maximum() const {
>   auto ret = this;
>
>   while (ret.right_) {
>       ret = ret.right_;
>   }
>
>   return ret;
>      }
> }
> ```
>
> It failed to compile and complaint that `cannot modify const
> expression ret`。
>
> Since `ret` is just a binding to a const class object, why can't
> I rebind it to another const class variable?
>
> Must I use pointers to cope with this?

No. You need to use http://dlang.org/phobos/std_typecons.html#.Rebindable

The thing to remember is that const is transitive, and when you have

const MyClass foo;

the reference itself is const, not just what it refers to. And the type
system doesn't have a way to represent a mutable reference to a const class
object, because it has no way of representing classes separately from
references to them. The two are, for better or worse, very much conflated as
far as the language is concerned. Pointers don't have that problem. e.g.

const(MyStruct)* foo;

but if you did

const(MyClass)* foo;

you'd just end up with a pointer to a const reference to a class object and
not a pointer to a const class object. Rebindable works around the problem
by being a mutable holder for the const reference to the class. It's a bit a
annoying and clunky, but it's a side effect of how there really isn't any
way in the language to represent class objects separately from the
references to them.

- Jonathan M Davis




More information about the Digitalmars-d-learn mailing list