News:

This week IPhone 15 Pro winner is karn
You can be too a winner! Become the top poster of the week and win valuable prizes.  More details are You are not allowed to view links. Register or Login 

Main Menu

c++ array tips - Why arrays of references are disallowed

Started by ben2ong2, October 06, 2006, 06:09:09 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

ben2ong2

PROBLEM: _d_e_e_f_@_t_e_l_e_p_o_r_t_._c_o_m_ (Derek Foster)

Why are arrays of references not allowed? This seems to me to be a very
arbitrary restriction on the language that is very inconvenient at times.


RESPONSE: You are not allowed to view links. Register or Login (Steve Clamage), 1 Dec 94

Because references are not and cannot be lvalues. Consider:
   T someObject;   // T is some type
   T& t = someObject;
   sizeof(t) == ???
   &t == ???
The "sizeof" a reference is the size of the object referenced, and
the "address-of" a reference is the address of the object referenced.
   sizeof(t) == sizeof(T)
   &t == &someObject

Now let's put references into an array.
   T& a[5] = { o0, o1, o2, o3, o4 }; // suppose this were allowed
By definition of arrays and pointers,
   &(a[1]) == a + 1
By definition of references
   &(a[1]) == &o1
These can't both be true.

In addition, you can step through an array by sizeof its element type.
But the sizeof the element type is supposed to be sizeof T, which is
probably not the same size as that taken up by a reference. (Notice this
makes problematical the meaning of the "a+1" above.)

So to allow arrays of references we have to change significantly either the
semantics of arrays or the semantics of references -- but only for the case
of an array of references. In exchange for this unpleasant complication, I
don't believe we get any additional functionality.

Instead of the kind of references we have in C++, I suppose we could
have an automatically-dereferenced pointer type, which would be an lvalue.
We could have one syntax for getting the address of and the size of the
auto-pointer, and another for the thing pointed to. But that isn't C++.


You are not allowed to view links. Register or Login
You are not allowed to view links. Register or Login