ref和指针之间的不同行为 [英] Different behavior between ref and pointer
问题描述
int main()$ b这是一个奇怪的事,我遇到了, $ b {
int i {5};
void * v =& i;
int * t = reinterpret_cast< int *>(v);
int u = reinterpret_cast< int&>(v);
int i2 = * t;
}
t正确为5,u为垃圾。
发生了什么事?
code>存储
i
的地址,这就是你所说的垃圾。 (它不是真的垃圾,但是价值本身是无意义的,除了在程序的这个特定运行中的地址 i
)。 u
存储与 v
相同的值(按位),但重新解释为整数,因此它是垃圾。
t
不是5。或者如果是,这是一个极不可能的巧合。 t
是 i
的地址, i
是5 ,因此 * t
(即 t
解除引用)为5。
This is just an oddity I ran into and can't quite understand what's happening.
int main()
{
int i{ 5 };
void* v = &i;
int* t = reinterpret_cast<int*>(v);
int u = reinterpret_cast<int&>(v);
int i2 = *t;
}
t is correctly 5 and u is garbage.
What's going on?
v
stores the address of i
, which is, as you put it, garbage. (it's not really garbage, but the value itself is meaningless, except as it is the address of i
in this particular run of the program). u
stores the same value (bitwise) as v
, but reinterpreted as an integer, so it is "garbage".
t
is not 5, as you claim. Or if it is, it's an extremely unlikely coincidence. t
is the address of i
, and i
is 5, so *t
(that is, t
dereferenced) is 5.
这篇关于ref和指针之间的不同行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!