rebind of const class variables

ketmar via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jan 20 06:14:00 PST 2015


On Tue, 20 Jan 2015 09:29:45 +0000
qqiang via Digitalmars-d-learn <digitalmars-d-learn at puremagic.com>
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.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 181 bytes
Desc: not available
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20150120/d2e6bc10/attachment.sig>


More information about the Digitalmars-d-learn mailing list