Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the address of a reference to a dereferenced pointer the same as the address of the pointer?

In C++, is the address of a reference to a dereferenced pointer guaranteed to be the same as the address of the pointer?

Or, written in code, is the following assertion guaranteed to always hold true?

SomeType *ptr = someAddress;
SomeType &ref = *ptr;
assert(&ref == ptr);
like image 367
Jesper Avatar asked May 19 '11 14:05

Jesper


4 Answers

Yes, that is correct and will always be true.

Reference is nothing but an Alias of the type which it is referring to. It does not have a separate existence, it is always tied up to the one it is referring.

like image 100
Alok Save Avatar answered Nov 01 '22 12:11

Alok Save


Yes, provided of course that someAddress is not a null pointer, or otherwise not allowed to be dereferenced. In that case, behavior is undefined, although your implementation might well behave as though they are equal, especially with low optimization levels.

If you want to be precise, then &ref isn't really the "address of a reference", it's the "address of the referand of a reference". Since ref was bound to *ptr, that means the referand of ref and the referand (or pointee if you prefer) of ptr are the same object, and hence the two addresses &ref and ptr are equal.

And as Bo points out, what you're comparing &ref with is the "value of the pointer", or the "address stored in the pointer", rather than "the address of the pointer".

like image 31
Steve Jessop Avatar answered Nov 01 '22 12:11

Steve Jessop


Yes, if the reference itself has an address, it's managed by the implementation and not accessible from code. In any case, it's just a different name for the same object.

like image 2
Cat Plus Plus Avatar answered Nov 01 '22 13:11

Cat Plus Plus


Yes, your understanding is correct. And for 99.(9)% of the code in the world, your code will be correct. For the pedants in the audience (myself among them), this assertion is not always true:

SomeType *ptr = someAddress;
SomeType &ref = *ptr;
assert(&ref == ptr);

Consider this program:

#include <cassert>
struct SomeType { void* operator&() { return 0; } };
int main() {
  SomeType *ptr = new SomeType;
  SomeType &ref = *ptr;
  assert(&ref == ptr);
}
like image 1
Robᵩ Avatar answered Nov 01 '22 12:11

Robᵩ