Is there any way to find the address of a reference?

References don't have their own addresses. Although references may be implemented as pointers, there is no need or guarantee of this.

The C++ FAQ says it best:

Unlike a pointer, once a reference is bound to an object, it can not be "reseated" to another object. The reference itself isn't an object (it has no identity; taking the address of a reference gives you the address of the referent; remember: the reference is its referent).

Please also see my answer here for a comprehensive list of how references differ from pointers.

The reference is its referent


NO. There is no way to get the address of a reference.
That is because a reference is not an object, it is an alias (this means it is another name for an object).

int  x = 5;
int& y = x;

std::cout << &x << " : " << &y << "\n";

This will print out the same address.
This is because 'y' is just another name (an alias) for the object 'x'.


The ISO standard says it best:

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

I don't like the logic a lot of people are using here, that you can't do it because the reference isn't "guaranteed to be just a pointer somewhere anyway." Just as int x may be only a processor register with no address, but magically becomes a memory location when & x is used, it still may be possible for the compiler to allow what you want.

In the past, many compilers did allow exactly what you're asking for, eg

int x, y;
int &r = x;
&r = &y; // use address as an lvalue; assign a new referent

I just checked and GCC will compile it, but with a strongly worded warning, and the resulting program is broken.

Tags:

C++

Reference