问题
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?
回答1:
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.
回答2:
printf("%x %x\n", u, v);
for me prints:
39fdb8 39fdb8
Not garbage, but the value of v
.
回答3:
u is int v is pointer *v is int, but we should the following code can output 5 5
#include <iostream>
using namespace std;
int main()
{
int i{ 5 };
void* v = &i;
int* t = reinterpret_cast<int*>(v);
int u = reinterpret_cast<int&>(*(int*)v);
int i2 = *t;
std::cout << *t << std::endl;
std::cout << u << std::endl;
return 0;
}
来源:https://stackoverflow.com/questions/21177634/different-behavior-between-ref-and-pointer