13

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?

Gordon Gustafson
  • 40,133
  • 25
  • 115
  • 157
skydoor
  • 25,218
  • 52
  • 147
  • 201
  • 8
    Because Bjarne Stroustrup says so. – David Pfeffer Feb 23 '10 at 20:52
  • Possible duplicate: http://stackoverflow.com/questions/1164266/why-arrays-of-references-are-illegal – Kirill V. Lyadvinsky Feb 23 '10 at 21:26
  • 1
    Such boring answers. How about answering why the standard disallows it? Is there some fundamental reason why c++ can't support rebinding references? – deft_code Feb 23 '10 at 22:31
  • 2
    @Caspin: When limited in this way a reference can be implemented as an alias in the symbol table (i.e. it is not allocated it's own storage and has no existence once code generation happens), and because c++ inherited pointers from c it has no need to build more complicated behaviors into references. – dmckee --- ex-moderator kitten Mar 03 '10 at 19:44

5 Answers5

16

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.

Péter Török
  • 114,404
  • 31
  • 268
  • 329
  • 1
    Now that we have array initialization in C++11, it seems like there could be arrays of references. – Gurgeh Jun 25 '12 at 12:21
  • 1
    there has always been array initialization, and I do not see why int& refs[2] = {x, y}; is immoral. – Slava May 20 '13 at 10:23
  • "Pointers are mutable (if non-const), references never. " This isn't true for references that are members of a class. It's also not true for const pointers in a class. At least since c++20. That said, references don't have identity except when they are members of a class where they can be reseated/reassigned indirectly. – doug Dec 06 '22 at 23:08
12

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.

Kirill V. Lyadvinsky
  • 97,037
  • 24
  • 136
  • 212
  • rvalue references ARE NOT references to references, although their syntax `&&` might suggest so. – fredoverflow Feb 23 '10 at 21:03
  • 8
    -1 Very rare for me to downvote, but I mean really, what is the point of this answer? Some posters here seem to imagine the standard is a kind of holy book. First you need a language that is useful and makes sense, only then is a standard necessary. – Bill Forster Feb 23 '10 at 21:04
  • 4
    @Bill: How does one first have a language then a standard, when languages are defined by standards? The C++ language is *defined* by the standard alone; any question regarding C++ can only be answer with information from the standard. What would you propose as an answer instead? – GManNickG Feb 23 '10 at 21:07
  • 1
    @GMan. You misunderstand how the world works. C++ standardization occurred after C++ was created and found useful. Do you really think it is plausible to spend a vast amount of effort creating an enormously detailed standard (like the C++ standard) as the first step in launching the language ? No, these things work organically, someone has an idea, makes a toy compiler, shows it to other people, it builds momentum (or not), eventually you may get something like the C++ standard. I would propose as an answer an explanation of why this feature of C++ makes sense. Others have provided that. – Bill Forster Feb 23 '10 at 21:16
  • 1
    FredOverflow, seems to be you are right. There are still no pointers to rvalue references. – Kirill V. Lyadvinsky Feb 23 '10 at 21:16
  • I thought the question asked to provide some reasoning behind this. – Slava May 20 '13 at 10:26
12

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.

Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
  • 1
    This is the only answer that actually explains why the standard doesn't want any implementation to allow arrays of references. – Chani Dec 15 '15 at 06:34
5

C++ Standard 8.3.2/4:

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

The reasoning behind this is that a reference doesn't exist in and of itself at run-time. A reference merely is another name for a location. They are immutable.

David Pfeffer
  • 38,869
  • 30
  • 127
  • 202
-1

I think we probably need to start by reiterating that arrays of references are used all the time in Java and Python. In fact, a Java programmer never really tries to directly use addresses of data(pointers). Consider the following totally legal Java example using an array of references:

String[] array_of_references = new String[2]; // create array of String object references
array_of_references[0] = "Hello"; // "Hello" is a string object reference
array_of_references[1] = "World!";
print(array_of_references[0].toLowerCase()); // use dot to access method of ref.
// prints hello

I am lying a little here because references in C++ are not exactly the same as references in Java.

The difference that makes it impossible to create an array of references in C++ is the restriction that every reference in C++ has to *always*(in all scopes) be assiciated with some variable *name* in the program. In other words, to create an array of references in C++, you are required to manually name every element of the array, which goes against the usefulness of arrays. Here is my (brave yet pitiful) attempt to implement a C++ array-of-references of fixed size 3:

class ArrayOfReferences_size3{
  public:
    // constructor
    ArrayOfReferences_size3(int &el_1, int &el_2, int &el_3):
    first_el(el_1), second_el(el_2), third_el(el_3) {}

    int& first_el; // gotta name it again
    int& second_el; // gotta name it again
    int& third_el; // gotta name it again
};

int main() {
  int el_1 = 1; // gotta name the value
  int el_2 = 2; // gotta name the value
  int el_3 = 3; // gotta name the value
  ArrayOfReferences_size3 my_array(el_1, el_2, el_3);
  cout << my_array.first_el 
       << my_array.second_el 
       << my_array.third_el << "\n";
}

Java can allow references to be unnamed because java references can represent thier own value like c++ pointers can -- they don't need to be bound to a name. In fact, Java references can have a null value just like pointers can have nullptr value.
In the example below, notice how the String object reference "Hello" is unnamed and the only way to reach it is by indexing into the array:

array_of_reference[0] = "Hello"; // Impossible with C++ references
Harsh Verma
  • 529
  • 6
  • 10
  • 1
    1. Danging references are legal by themselves, it's only illegal to dereference them. 2. You don't have to bind a reference to a variable, any object is enough (unnamed temporary objects are not variables, you references can point to those). 3. C++ references can too be unnamed and too occupy memory, unless optimized away. (Not sure if comparison with Java was intended to imply otherwise or not.) – HolyBlackCat Dec 06 '22 at 22:24
  • @HolyBlackCat 1. I am having a hard time understanding how the possibiliy of dangling references is related to something I have said above. Can you elaborate ? 2. The reference that will eventually point to the unnamed temporary object will have a variable name. Am I misunderstanding the concept of a variable name ? 3. Can you point me to an example where references are allowed to not bind to a variable name? Yes, you are right about the memory -- I will update the answer. – Harsh Verma Dec 06 '22 at 23:10
  • The concept of a reference doesn't have anything to do with names; it has to do with referencing _objects_. Not all references even have to be given a variable name. Simplest counter-example: `void foo(const int&);`; we have a function that takes a reference as a parameter, but the reference parameter has no name. You can call it `foo(42)`, and this will be valid as well -- and now neither the reference nor the referee are named (unnamed temporary + const lifetime extension). – Human-Compiler Dec 06 '22 at 23:39
  • @Human-Compiler Even if its possible, how do you use that unnamed integer in the body of the `foo` function ? Even though the concept of a reference doesn't have to do with binding to variable names, c++ thinks otherwise. – Harsh Verma Dec 06 '22 at 23:45
  • You don't, but that's not the point. The point is your answer seems to indicate a misunderstanding of what references are. References have zero to do with names, they have to do with object lifetimes. And the reason they aren't allowed has already been answered _correctly_ by other answers. I recommend mmx's answer (https://stackoverflow.com/a/2321613/1678770) for some good rationale. – Human-Compiler Dec 06 '22 at 23:46
  • @Human-Compiler even though the `concept` of references doesn't have to do with names, a language implementer can `choose` to relate them if he/she wants, and I think the implementors of C++ are doing that. – Harsh Verma Dec 06 '22 at 23:52
  • 1
    I highly recommend you take a look through [this list of recommended C++ reading](https://stackoverflow.com/a/388282/1678770) and thumb through something that covers reference value-categories in depth. Compiler developers are working off of the C++ ISO spec, which indicates _exactly_ how/where references can operate -- which, primarily, comes from value categories (a concept stemming from lifetimes). Some educational reading might help correct some misunderstandings. – Human-Compiler Dec 07 '22 at 00:25