It's worse than I thought
Sönke Ludwig
ludwig at informatik_dot_uni-luebeck.de
Fri Nov 30 05:19:43 PST 2007
Walter Bright wrote:
> Janice Caron wrote:
>> It's worse than I thought. This compiles and runs, both in D2.007 and
>> in D2.008
>>
>> void main()
>> {
>> const(int) ci = 1;
>> invariant(int) ii = 2;
>>
>> ++ci;
>> ++ii;
>> }
>>
>> It is now becoming quite clear that the "const mess" is very much
>> still with us, and this sort of thing really doesn't help D at all.
>
> It turns out that making a variable that is typed const (rather than
> storage class const) immutable makes it impossible to use const references:
>
> class C { }
> const(C) c;
> if (...)
> c = ...;
> else
> c = ...;
>
> So, variables that are typed const are rebindable. Note that this
> doesn't break const, as you can always make a copy of a const. To get a
> non-rebindable const:
>
> const C c;
I've noticed some things that seem to be inconsistent with this behavior
for local variables and where I've not found a workaround for (with the
exception of casts):
1. Arrays or associative arrays of references to const instances:
class C {}
const(C)[] a;
const(C)[string] b;
It seems to be impossible here to make the array elements assignable,
while at the same time keeping the class instances const. I currently
need this in a function, where I'm getting a const array of instances
and need to build a map to those.
void fn( in C[] objs ){
const(C)[string] map;
map["test"] = objs[0]; // error, not mutable
}
2. Class references as members:
class D {
const(C) c;
const C d;
this( C c ){
this.c = c; // error
this.d = d; // works, but, of course, only inside of the constructor
}
}
More information about the Digitalmars-d
mailing list