Why doesn't this reinterpret_cast compile?

前端 未结 11 687
暗喜
暗喜 2020-12-04 16:32

I understand that reinterpret_cast is dangerous, I\'m just doing this to test it. I have the following code:

int x = 0;
double y = reinterpret_c         


        
11条回答
  •  执笔经年
    2020-12-04 16:54

    Perhaps a better way of thinking of reinterpret_cast is the rouge operator that can "convert" pointers to apples as pointers to submarines.

    By assigning y to the value returned by the cast you're not really casting the value x, you're converting it. That is, y doesn't point to x and pretend that it points to a float. Conversion constructs a new value of type float and assigns it the value from x. There are several ways to do this conversion in C++, among them:

    int main()
    {
        int x = 42;
        float f = static_cast(x);
        float f2 = (float)x;
        float f3 = float(x);
        float f4 = x;
        return 0;
    }
    

    The only real difference being the last one (an implicit conversion) will generate a compiler diagnostic on higher warning levels. But they all do functionally the same thing -- and in many case actually the same thing, as in the same machine code.

    Now if you really do want to pretend that x is a float, then you really do want to cast x, by doing this:

    #include 
    using namespace std;
    
    int main()
    {
        int x = 42;
        float* pf = reinterpret_cast(&x);
        (*pf)++;
        cout << *pf;
        return 0;
    }
    

    You can see how dangerous this is. In fact, the output when I run this on my machine is 1, which is decidedly not 42+1.

提交回复
热议问题