When I run this code:
uint8_t stackVar = 0;
void* ptr = &stackVar;
uint8_t& ref = reinterpret_cast<uint8_t&>(ptr);
std::cout << (void*)&ref << std::endl;
std::cout << ptr << std::endl;
std::cout << (void*)&stackVar << std::endl;
I get this output:
0x22fe30
0x22fe3f
0x22fe3f
At least in my estimation I should get the same number for all three of these statements. What is going on here?
uint8_t& ref = reinterpret_cast<uint8_t&>(ptr);
You are casting a pointer ( void*
) to a reference. This will result in the same uint8_t
, because it will make a reference to a temporary uint8_t
, which you created out of a void pointer. 导致相同的uint8_t
,因为它将引用您从void指针创建的临时uint8_t
。 And because a new uint8_t
is created, you are getting different addresses.
Maybe you meant uint8_t& ref = reinterpret_cast<uint8_t&>(stackVar);
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.