Why doesn't this reinterpret_cast compile?

前端 未结 11 683
暗喜
暗喜 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:46

    Reinterpret cast allows you to reinterpret a block of memory as a different type. This has to be performed on pointers or references:

    int x = 1;
    float & f = reinterpret_cast(x);
    assert( static_cast(x) != f );   // !!
    

    The other thing is that it is in fact a quite dangerous cast, not only due to strange values coming out as results, or the assert above not failing, but because if the types are of different sizes, and you reinterpret from 'source' to 'destination' types, any operation on the reinterpreted reference/pointer will access sizeof(destination) bytes. If sizeof(destination)>sizeof(source) then that will step beyond the actual variable memory, potentially killing your application or overwritting other variables other than the source or destination:

    struct test {
       int x;
       int y;
    };
    test t = { 10, 20 };
    double & d = reinterpret_cast( t.x );
    d = 1.0/3.0;
    assert( t.x != 10 ); // most probably at least.
    assert( t.y != 20 );
    

提交回复
热议问题