对取消引用的指针的引用的地址与指针的地址相同吗?
在C++中,对取消引用的指针的引用的地址是否保证与指针的地址相同?
或者,用代码编写,以下断言是否保证始终成立?
SomeType *ptr = someAddress;
SomeType &ref = *ptr;
assert(&ref == ptr);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,这是正确的,并且永远都是正确的。
引用只不过是它所引用的类型的别名。它没有单独的存在,它总是与它所指的那个存在联系在一起。
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.
是的,当然前提是
someAddress
不是空指针,否则不允许取消引用。在这种情况下,行为是未定义的,尽管您的实现可能表现得好像它们是相等的,尤其是在优化级别较低的情况下。如果你想精确一点,那么
&ref
并不是真正的“引用的地址”,它是“引用的引用对象的地址”。由于ref
绑定到*ptr
,这意味着ref
的引用对象和ptr 的引用对象(如果您愿意,也可以称为指针对象)
是同一个对象,因此两个地址&ref
和ptr
是相等的。正如 Bo 指出的那样,您要比较
&ref
的是“指针的值”,或“指针中存储的地址”,而不是“指针的地址” 。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". Sinceref
was bound to*ptr
, that means the referand ofref
and the referand (or pointee if you prefer) ofptr
are the same object, and hence the two addresses&ref
andptr
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.
是的,你的理解是正确的。对于世界上 99.(9)% 的代码,您的代码都是正确的。对于观众中的学究们(其中包括我自己)来说,这种说法并不总是正确的:
考虑这个节目:
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:
Consider this program: