简体   繁体   中英

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);

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.

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

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM