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

Sergey Gromov snake.scaly at gmail.com
Wed Feb 20 10:31:11 PST 2008


Janice Caron <caron800 at googlemail.com> wrote:
> On 20/02/2008, Sergey Gromov <snake.scaly at gmail.com> wrote:
> > This means that for int,
> > which is not referencing anything,
> >
> > const(int) t;
> >
> > is completely and safely equivalent to
> >
> > int t;
> 
> [...]
> One of the reasons that that syntax was ditched was because it was
> damnably confusing, and got many, many complaints from people who were
> using it. Not only did const(int) mean "mutable int", but even if you
> could get your head round that one, it turned out that
> 
>     const (int *)* p;
> 
> and
> 
>     const (int **) p;
> 
> were completely equivalent.

Pointers ruin my beautiful theory.  :-)

They are different.  They do not generalize with references.  So I 
propose to outlaw them completely: let them be an advanced, unsafe, low-
level feature.  So that pointers can never be const, and an explicit 
cast is /always/ required to convert from reference to pointer and back.

To do this, references must be powerful enough to replace pointers for 
any high-level tasks.  For instance, structs should always be passed by 
reference unless they are invariant and small.

> And I have absolutely no idea what the
> syntax for array of const ints was. Was it "const(int)[]"? Was it
> something else?

Easy.  An array of const ints is "const(int[]) x;"  You can't change 
ints, you can't change length nor ptr either.  You can replace the whole 
thing though because x is not const (is outside the parentheses).

> I mean, it was just too confusing for words. No way
> can we /ever/ go back to that. For any type, T, const(T) absolutely
> /must/ mean that T is const.

My concept is very simple.  Everything within the scope of const is 
const, everything outside is not.

The confusion arises in two cases:

a) trying to apply constness to primitive types.  It really may be hard 
to understand why const(int) does nothing.  But you don't need to use 
this syntax in everyday programming.  What you really need is const(T) 
to behave consistently for different T.  C++ allows to call a destructor 
for int for exactly the same reason, and

b) when you use const for pointers and experience completely different 
behaviour from references.  This is because pointers are too different, 
and you can't do without pointers in D at the moment.  This should be 
fixed.

-- 
SnakE



More information about the Digitalmars-d mailing list