Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

reference

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

Making it more specific: The address of the variable itself and not the address of the variable it is initialized with.

like image 471
Sandeep Avatar asked Dec 23 '09 04:12

Sandeep


People also ask

What is the address of a reference?

The address of a reference is the address of the aliased object or function. An lvalue reference type is defined by placing the reference modifier & or bitand after the type specifier.

Do references have memory addresses?

Regardless of how a reference is implemented, a reference has the same memory address as the item it references. A reference does not have an address at all. References are not objects, don't have memory or a size and you cannot std::memcpy them.

Is address and reference same?

An address is a number that corresponds to a place in memory. A reference is a name that refers to an existing object, rather than being it's own object.

Can you change the address to which a reference refers?

A references is stored as a pointer, so you can always change where it points to as long as you know how to get its address.


2 Answers

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

like image 89
Brian R. Bondy Avatar answered Sep 19 '22 17:09

Brian R. Bondy


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'.

like image 33
Martin York Avatar answered Sep 19 '22 17:09

Martin York