Different behavior between ref and pointer

一世执手 提交于 2019-12-12 01:12:39

问题


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

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