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

Walter Bright newshound1 at digitalmars.com
Tue Feb 19 20:22:30 PST 2008


Sergey Gromov wrote:
> Walter Bright <newshound1 at digitalmars.com> wrote:
>> The concept of having a mutable reference to immutable data is 
>> fundamentally flawed because it breaks the concept of what a reference 
>> is. A reference is not separable from what it refers to. If they were 
>> separable, they would be syntactically and semantically the same thing 
>> as pointers, and there would be no point whatsoever to even having a 
>> reference type.
> 
> A reference refers to data which is outside of the reference's body.  
> This is the concept.  A reference in a book, a C pointer, and a C++ 
> reference are all realizations of this concept.  The reason for C++ 
> references to be immutable is obvious: the C++ designers wanted the 
> C::operator=(C&) to work.
> 
> D supports mutable references, so D references are not C++ references.  
> D references are not the same as the data they refer to.  They are much 
> closer to pointers than in C++.
> 
> The difference is in syntax.  The point in having references in the 
> language is the same as in C++: to use the same syntax for accessing 
> objects, their members, and primitive types.

That is only a small part of why D classes are reference types. The 
major reason is that polymorphism doesn't work for value types, it cries 
out for reference types. Value and reference types have different uses.

> This is required for 
> proper generalization, and also simplifies program code.
> 
> This is why references must support all possible type variants: they are 
> instruments of generalization, so power of D templates depends directly 
> on the power of references.
> 



More information about the Digitalmars-d mailing list