Why can't we define re-assignable const reference variable?

Sönke Ludwig ludwig at informatik_dot_uni-luebeck.de
Mon Feb 18 00:08:31 PST 2008


Janice Caron schrieb:
> On 17/02/2008, Sönke Ludwig <ludwig at informatik_dot_uni-luebeck.de> wrote:
>> Show me how I can maintain a simple map of class instances, which I get as
>> const(C) from somewhere else, i.e. I have to accept the const here.
>>
>> example:
>>
>> const(C)[string] map;
>>
>> <- completely useless - you can do nothing with this construct
> 
> So change it to
> 
>     const(C)*[string] map;
> 
> Now you've a map of mutable pointers, indexed by string. It's not hard.

Since C is a class, const(C)* will mean a mutable pointer to a const class
reference, which is not even allocatable with a simple syntax (was brought
up here a while ago), also this would be an additional allocation, just
like with the struct workaround (see below).

Generally, I think that it is very desirable to be able to handle the
reference/pointer part of a class C separate from the actual data in this
respect. After all they are completely distinct in the underlying
implementation.

> 
> 
>> or to use a struct S { const(C) obj }
> 
> That probably won't work in the future. You're basically exploiting a
> bug there, and I imagine that soon it will be fixed.
> 

No, was talking about creating a struct where the const reference stored on
the heap - a mutable pointer to this struct is then stored in the map.
If a new object is to replace an array entry, a new struct is allocated
and a pointer to this new struct replaces the old one.

Sorry, forgot an example - this is what I was thinking about:
struct S { const(C) inst; }
S*[string] map;
map["hello"] = new S(someinst);

All of this is and should always be possible, it does not break any
const principle or anything. It's just that it requires an additional
heap allocation and a lot of additional typing which should really not
be necessary for such a basic thing.



More information about the Digitalmars-d mailing list