As the title itself mentions - why are pointer to a reference illegal, while the reverse is legal in C++?
-
1Looks like someone took my words seriously from here stackoverflow.com/questions/4632528/… .... that's good :DSarfaraz Nawaz– Sarfaraz Nawaz2011-01-08 06:59:59 +00:00Commented Jan 8, 2011 at 6:59
-
1Anyway, +1 for the good question. even I want to know the rationale!Sarfaraz Nawaz– Sarfaraz Nawaz2011-01-08 07:00:34 +00:00Commented Jan 8, 2011 at 7:00
-
1@Nawaz: Your guess is correct.Mahesh– Mahesh2011-01-08 07:04:20 +00:00Commented Jan 8, 2011 at 7:04
5 Answers
A pointer needs to point to an object. A reference is not an object.
If you have a reference r, once it is initialized, any time you use r you are actually using the object to which the reference refers.
Because of this, you can't take the address of a reference to be able to get a pointer to it in the first place. Consider the following code:
int x;
int& rx = x;
int* px = ℞
In the last line, &rx takes the address of the object referred to by rx, so it's exactly the same as if you had said &x.
3 Comments
The high-level concept that references implement is just another name for an existing object. You can have a pointer to an object (or function), but you can't have a pointer to an object's name. For this very reason, the idea of a pointer to a reference makes no sense. In other words, references are immaterial, in general case they simply do not exist in memory. They don't exist as something that can be pointed to.
It is true that in many cases in practice references do occupy memory (and are implemented as pointers in disguise). But that just an implementation detail specific to some particular contexts. In general case references do not occupy memory, as is explicitly stated in the language specification which immediately follows from the language specification.
37 Comments
It is unspecified whether or not a reference requires storage There shall be no references to references, no arrays of references, and no pointers to references.What would be the difference between a pointer to a reference (to the object) and a pointer to the actual object? The reference cannot be changed to refer to another object. Just use a regular pointer to the object in question.
On the other hand, a reference to a pointer, like any other reference, gives you a modifiable handle to a particular variable. It happens to be a pointer in this case.
Comments
Because a reference is not a thing that can be pointed at, which in turn is because it does not actually have to be represented anywhere in memory. References exist to give alternate names to already-existing things. You can get a pointer to the renamed thing, but that is a pointer to a value, not a pointer to a reference.
Comments
Suppose "int *&X" is legal, because reference is just another name of an object, the expression is equal to "int *X" and is not useful.