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

拈花ヽ惹草 提交于 2020-01-12 06:58:11

问题


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

回答1:


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.




回答2:


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




回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/6060392/is-the-address-of-a-reference-to-a-dereferenced-pointer-the-same-as-the-address

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!