On Tue, 20 Jan 2015 09:29:45 +0000 qqiang via Digitalmars-d-learn <[email protected]> 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?
Jonathan explains it very well. i can add the only thing: don't use
`const` until you forced to. ;-) C++ programmers tend to "help
compiler" with const methods and so on. just don't do that in D until
you become friends with D constness.
sure, you can cast `const` away in your code, but using `cast` is a
good sign of taking the wrong way.
signature.asc
Description: PGP signature
