It's worse than I thought
Sönke Ludwig
ludwig at informatik_dot_uni-luebeck.de
Mon Dec 3 05:32:47 PST 2007
Walter Bright schrieb:
> Sönke Ludwig wrote:
>> 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
>> }
>> }
>
> There isn't much to be done about this problem except make the
> implementation of the class itself const.
As far as I understand it, it's currently only possible to have mutable
references to const/invariant data when using local/global variables,
but not inside classes/structs/arrays.
Now, after playing some more, I have made some classes "invariant class
C {}" (a really nice feature). I think it is absolutely _vital_ to be
able to have at least arrays/maps of such classes. However, in this case
it is not even possible to cast away the invariant, as it now belongs to
the type C.
The workarounds I've found are to make a proxy "struct CS { C c; }" and
store that, or to cast the class reference to void*. But both solutions
are ugly.
Having said that, especially after using the system now for more than
some const methods, I actually like the current system - of course with
the above exception :) - and although it is of course quite different to
C++'s solution, it's actually quite easy to grasp.
PS: on a side note, I found that invariantness is lost in a few
situations, when a const modifier is applied. Unfortunately I don't have
an example at hand, will post one if I'm hitting it again.
More information about the Digitalmars-d
mailing list