const and immutable objects

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Mon Aug 31 12:51:42 PDT 2009


Jeremie Pelletier wrote:
> Andrei Alexandrescu Wrote:
> 
>> Jeremie Pelletier wrote:
>>> Graham St Jack Wrote:
>>>
>>>> On Sun, 30 Aug 2009 21:28:18 -0400, Jeremie Pelletier wrote:
>>>>
>>>>
>>>>> I agree that D lacks a mechanism to separate the object from it's
>>>>>  reference. Maybe syntax like the following could be used to
>>>>> apply the storage class to the object value, and not the
>>>>> reference value:
>>>>>
>>>>> class Foo; void bar(in Foo& foo) {}
>>>>>
>>>>> It's quite ugly and C-like, but that's the first thing that came
>>>>> to mind. The reference value is unique to the current method and
>>>>> shouldn't share the same storage qualifiers as it's referenced
>>>>> memory.
>>>> I think the time for pining over this particular syntax feature of
>>>> D is over - as nice as it would be to be able to fix the problem in
>>>> the language, it would be too disruptive right now.
>>> I think it would be better to fix it in D2  instead of patching a
>>> language design flaw with a template. It wouldn't be the first time
>>> D2 has changes that breaks existing code anyways (and the upcoming
>>> T[new] will definitely break a lot of code, so does shared when it
>>> works, etc), so it would be less disruptive to do it now than never
>>> do it.
>> I agree with the sentiment. The issue is, however, that the change adds 
>> a fair amount of complexity to the const system for an arguably 
>> not-often-used need.
>>
>> Andrei
> 
> Correct me if I'm wrong, but I don't see how complex that could be. I assume the compiler already makes the difference between the reference value and the referenced object, all that needs to be done is to reflect that view in the syntax.

There was a lot of discussion around "head constness" and "tail 
constness" a while ago in this newsgroup. The general sentiment was that 
adding one or both of these nuances would make const too difficult to 
bother with.

> Maybe a .ref property?
> 
> class A {}
> void foo(in A a) {
>     a = new A(); // fail, cannot modify const
>     a.ref = new A(); // ok, only reference value is modified
> }
> 
> If you want to make the reference immutable, you can use the .ref on the class identifier:
> 
> const(A.ref)[] AList; // slice of const references to A
> 
> It may not be perfect, but I do firmly believe that the D syntax needs a mechanism to separate references from objects, even if rarely used, I can think of at least 15-20 places in my code I had to use workarounds for such cases.
> 
> I don't think A* should be used since that is a pointer to an object reference, it would break too much code and be incredibly hard to track back. A& looks nice because that's how references are already handled in C++, and we'd  get const(A)& the same way we get const(int)*.

There would still be a problem with struct objects.

Andrei




More information about the Digitalmars-d mailing list