Const sucks
Robert Fraser
fraserofthenight at gmail.com
Mon Sep 10 22:38:54 PDT 2007
Walter Bright Wrote:
> Robert Fraser wrote:
> > That worries me (not that case in particular, but general constness +
> > classes). My coding style tends to use a lot of invariant objects
> > (for thread safety reasons), so I get the feeling that the inability
> > to *easily* express a mutable reference to a constant class will bite
> > me like a ferret.
>
> It worries me in the abstract, but I've not been able to find a real
> case where it matters.
Here's an easy one: returning constant class references from an opApply. Or, if you argue the variable holding the references is reassigned each time, how about iterating through constant nodes in a linked list?
const(node) current;
while(current = current.next)
{
....
}
... or really any sort of iteration using the same variable.
Or how about (took looking at half a page of code to find an example similar to this):
const(Foo) foo = bar();
if(null is foo)
foo = new Foo();
Obviously, there may be a way around this, but I use this idiom fairly frequently, especially when getting stuff that might or might not be in an associative array/map.
... Or what about cached objects, which are passed to the function handling the cache as const (since the function handling the cache shouldn't be changing them), but the references the cache holds are constantly changing?
... I could go on all day like this. Not that any of these are insurmountable (I'd just stop using const for class references altogether and cast when I was sending stuff to a library that wanted it, so there's a way to surmount it in my own code), but to make const usable, these cases need to be considered.
In fact, for curiosity's sake, I just ran Eclipse's "use final when possible" on Descent's (incomplete) Java port of the DMD front-end, and it looks like a little more than _half_ of the class references were reassigned sometime during their lifespan. None of these class references could be made to point to constant data.
More information about the Digitalmars-d
mailing list