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

Sergey Gromov snake.scaly at gmail.com
Mon Feb 18 01:23:16 PST 2008


Janice Caron <caron800 at googlemail.com> wrote:
> I say again, there is no way to express "mutable reference to const
> data" in D, and any method you come up with to allow that would be (a)
> incredibly confusing, and (b) would break generic programming and/or
> the type system.

One can safely assume that a variable x of type int with a value 4 in it 
is a mutable reference to an object 4 of type invariant(int).  That is, 
all variables of primitive types in D (as well as in other languages) 
are either mutable or immutable references to invariant objects.

Class type variables in D are either mutable references to mutable 
objects, or immutable references to immutable objects.

Pointers are either mutable or immutable references to either mutable or 
immutable objects, except head-const variant.

Struct type variables are exactly like primitives if struct doesn't 
contain references somewhere.  I like to call them PODs.  Modifying a 
struct is generalised as replacing a reference to one immutable set of 
data with a reference to another immutable set of data, exactly as it is 
with primitive types.

Non-POD structs cannot be generalised as references.  Hence all the 
problems with them.

So, here is a table summarizing what current D constructs can do:

			ref		tgt
Primitive/POD:
			var		inv
			const		inv
			inv		inv
Class:
			var		var
			const		const
			inv		inv
Pointer:
			var		var
			var		const
			var		inv
			const		const
			const		inv
			inv		inv

The left column is a reference type, the right column is a type of 
referenced object.  As you can see, the most generic type is pointer.  
That's why you suggest using it here and there.  But it's not the D way.  
In D, the class reference should be the most generic.  It should be safe 
to assume everything is reference when you write a template.  The 
mutable references to const objects are not breaking generic 
programming, but aiding it.

-- 
SnakE



More information about the Digitalmars-d mailing list