Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: why can't we have references to references or array of references?

Tags:

c++

reference

I noticed that there is no reference to reference but there is pointer to pointer, and also there is no an array of references but an array of pointers.

Could anybody give me any reason?

like image 578
skydoor Avatar asked Feb 23 '10 20:02

skydoor


3 Answers

Pointers are mutable (if non-const), references never. Thus there is no point having a pointer or reference to a reference.

Also, a reference must always refer to something - there is no such thing as a null reference. This is why there can be no arrays of references, as there is no way to default instantiate references inside an array to a meaningful value.

like image 156
Péter Török Avatar answered Nov 04 '22 17:11

Péter Török


It is according to C++ Standard 8.3.2/4:

There shall be no references to references, no arrays of references, and no pointers to references.

like image 11
Kirill V. Lyadvinsky Avatar answered Nov 04 '22 18:11

Kirill V. Lyadvinsky


A reference is an abstraction at the language level. It's an opaque way of aliasing a variable to another. While under the hood, the compiler is likely to work out references using pointers, they are very different things at a higher level. On the other hand, pointers are explicitly used by a programmer to achieve indirection. A pointer variable is a distinct variable from what it's pointed to. A reference should be thought as if it's simply an alias to the original variable, not as if it's yet another variable holding an address. Consequently, an alias for an alias of a variable would simply be an alias to the variable itself. Considering the binding a reference to a variable is a compile-time thing may help understanding the rationale behind this behavior.

With this reasoning, you can argue that since arrays are structures that store values, not variables, it doesn't make sense for them to be able to store aliases of variables. Basically, a reference variable (by which I mean the pointer, if exists, that may be used by the compiler to wire up the reference) is invisible to the programmer at the C++ level. If it was possible to declare arrays of references, the compiler probably needed to require constant indexes passed to the arrays to be able to resolve the binding at compile time.

like image 10
mmx Avatar answered Nov 04 '22 16:11

mmx