Const Ideas (and reference types)

Bill Baxter dnewsgroup at billbaxter.com
Fri Nov 30 12:51:56 PST 2007


Bill Baxter wrote:
> Janice Caron wrote:
>> Well, I'm still gunning for
>>
>>     const (X)& x;
>>
>> for mutable refs to const classes. Since I come from a C++ background,
>> & means "reference of" to me, and this reads straightforwardly as "x
>> is a reference to const X".
>>
>> Of course, x would be a reference even /without/ the ampersand - such
>> is the nature of classes in D. But writing it explicitly allows one to
>> put it outside the brackets.
> 
> I like where this is going, but my guess is that when/if Walter ever 
> introduces reference types, the syntax for reference-to-T will be "ref 
> T" like the parameter signature rather than C++'s  "T&".
> 
> So if you're going peel off the hidden ref, I think you might should 
> make it:
> 
>     ref X x --> const ref(T) x;
> or          --> const (T)ref x;
> or          --> ref const(T) x;
> 
> #3 seems pretty good to me.  But anyway no one knows what Walter will 
> decide to do.
> 
> About references generally, one big difference between C++ references 
> and D classes is that you can't reassign a C++ reference.
>      // C++
>      int& x = y;
>      x = z;  /// error

Er. Not 'error' per se, it just doesn't rebind x, it modifies y.

> In that sense, the C++ references themselves are always 'const' (aka 
> head-const / final).
> I seem to remember some example in Stroustrup that explained why this 
> behavior was important.  

I remembered.  You can't reassign them because it's ambiguous whether 
you want to make x just refer to the new thing or call the opAssign on 
the previously bound thing.  Ok, so D classes get around this by 
eliminating opAssign for classes and saying you can *only* rebind the 
reference.  But I don't think that will fly for references to structs or 
built-in value types.

--bb



More information about the Digitalmars-d mailing list