Why can't we define re-assignable const reference variable?
Sergey Gromov
snake.scaly at gmail.com
Mon Feb 18 07:34:18 PST 2008
Janice Caron <caron800 at googlemail.com> wrote:
> On 18/02/2008, Sergey Gromov <snake.scaly at gmail.com> wrote:
> > 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).
>
> Not unless you've redefined the word reference.
>
> At the ABI level, a reference is identical to a pointer. It occupies
> four bytes of space (eight on a 64 bit machine), and those four bytes
> contain an address. The difference between a reference and a pointer
> occurs at the syntax level, not the ABI level.
>
> What you've described there is not a reference at all - it's an int. A
> reference to an int would occupy eight bytes of memory (four for the
> reference, and four more for the int).
I'm talking from the standpoint of generalization which you so much care
about. When I generalize, I don't care how things are implemented.
It's behaviour that matters. If I create an algorithm that uses
references to invariant data, then it will work with anything that
/behaves/ like such references. Even if they are actually ints passed
by value.
Imagine a language with only one class of objects, that is, objects
passed by reference. Integer numbers are invariant objects of type int,
and an integer variable is a reference to an invariant object of type
int. Since the int objects are immutable, a compiler of this language
can safely optimize the code and keep the int object values in place of
references. This is what D does. It's an implementation detail. It's
an optimization which just happened to end up in language specs. This
optimization is so common that it's probably hard to believe that it's
only an efficient implementation of a generic concept of a reference.
--
SnakE
More information about the Digitalmars-d
mailing list