Any real example of reinterpret_cast changing a pointer value?

后端 未结 5 2322
灰色年华
灰色年华 2021-02-08 07:17

According to C++ Standard, a reinterpret_cast of a pointer T* to some other type pointer Q* can change or not change the pointer value dep

5条回答
  •  执笔经年
    2021-02-08 08:04

    class A1 { int a1; };
    class A2 { int a2; };
    
    class B: public A1, public A2 { };
    
    #define DBG(val)  cout << #val << ": " << val << endl
    
    // test code
    B b;
    DBG(&b);                                           // prints 0x42
    
    void *p_blank = &b;
    DBG(p_blank);                                      // prints 0x42
    A2 *p_a2 = &b; 
    DBG(p_a2);                                         // prints 0x46
    void *p_reinterpreted = reinterpret_cast(&b);
    DBG(p_reinterpreted);                              // prints 0x42
    A2 *p_reinterpreted2 = reinterpret_cast(&b);
    DBG(p_reinterpreted2);                             // prints 0x42
    

    A2 *p_a2 = &b means give me the pointer to an A2 object within the B object. reinterpret_cast(&b) means give me the pointer to b and treat it as an A2 pointer. The result of this reinterpret_cast has the type 'pointer to A2', therefore it produces no warning when assigned to a void* variable (or to a A2* variable).

提交回复
热议问题