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

Sergey Gromov snake.scaly at gmail.com
Sun Feb 17 20:06:45 PST 2008


Janice Caron <caron800 at googlemail.com> wrote:
> On 17/02/2008, Sergey Gromov <snake.scaly at gmail.com> wrote:
> > Janice Caron <caron800 at googlemail.com> wrote:
> > > On 17/02/2008, Sergey Gromov <snake.scaly at gmail.com> wrote:
> > > > So it's really strange that you can't declare
> > > > const(C) x;
> > >
> > > You can!
> >
> > But it wouldn't mean mutable reference to const data.
> 
> Of course not. That would be impossible.
> 
> You cannot have a mutable reference to const data in C++, so what's
> the big deal? The best you can achieve in C++ is a mutable /pointer/
> to const data, and that is also allowed in D.

You can't have a mutable reference to mutable data in C++, either.  D 
allows that.  Why allow one but deny the other, I don't get it.

> > This /looks/ like
> > const only affecting C
> 
> const is transitive, so it affects C, and everything referenced by C.
> It declares the four-byte reference on the stack that is C, to be
> const, and since const is transitive, that makes the instance of C's
> data on the heap const, and everything referenced therefrom.

Yes, the C and everything below is const. But why x ?  It doesnt belong 
to C, it's in my function scope.  It's not transitiviness that bothers 
me, but backward transitiviness.

> > but, in fact, constness is expanded over the
> > whole declaration.
> 
> Of course. Everything in the brackets is const. That's what's brackets
> are for - precedence. C is in the brackets; C is const.

But x is outside brackets !  Why is it const, too ?

> > I.e. the syntax for declaring reference to const is
> > already in the language,
> 
> You're going to have to clarify that, I'm afraid, as I don't
> understand. Are you referring to the function parameter syntax
> 
>     ref const(C) c
> 
> ? In this case, c is indeed rebindable, but only because an extra
> level of indirection has been silently added.

When I write, "const(C) x;", I mean, "C is const but x is not."  This is 
semantically correct because the assignment operator works with the 
reference directly when an object of the same type is assigned.  It's in 
the language specs.  There is no problem for the assignment to check at 
compile time if the x itself is const or not.

> > the question is, why it's not in the type
> > system.
> 
> I don't agree that that's even a reasonable question, because there is
> /not/ a syntax for "mutable reference to constant data" (not counting
> function parameters).

It could've been.  You wouldn't need to change the language syntax if 
you wanted to add one.

-- 
SnakE



More information about the Digitalmars-d mailing list