When to use reinterpret_cast?

前端 未结 11 1314
我寻月下人不归
我寻月下人不归 2020-11-22 08:41

I am little confused with the applicability of reinterpret_cast vs static_cast. From what I have read the general rules are to use static cast when

11条回答
  •  执念已碎
    2020-11-22 09:44

    Here is a variant of Avi Ginsburg's program which clearly illustrates the property of reinterpret_cast mentioned by Chris Luengo, flodin, and cmdLP: that the compiler treats the pointed-to memory location as if it were an object of the new type:

    #include 
    #include 
    #include 
    using namespace std;
    
    class A
    {
    public:
        int i;
    };
    
    class B : public A
    {
    public:
        virtual void f() {}
    };
    
    int main()
    {
        string s;
        B b;
        b.i = 0;
        A* as = static_cast(&b);
        A* ar = reinterpret_cast(&b);
        B* c = reinterpret_cast(ar);
    
        cout << "as->i = " << hex << setfill('0')  << as->i << "\n";
        cout << "ar->i = " << ar->i << "\n";
        cout << "b.i   = " << b.i << "\n";
        cout << "c->i  = " << c->i << "\n";
        cout << "\n";
        cout << "&(as->i) = " << &(as->i) << "\n";
        cout << "&(ar->i) = " << &(ar->i) << "\n";
        cout << "&(b.i) = " << &(b.i) << "\n";
        cout << "&(c->i) = " << &(c->i) << "\n";
        cout << "\n";
        cout << "&b = " << &b << "\n";
        cout << "as = " << as << "\n";
        cout << "ar = " << ar << "\n";
        cout << "c  = " << c  << "\n";
    
        cout << "Press ENTER to exit.\n";
        getline(cin,s);
    }
    

    Which results in output like this:

    as->i = 0
    ar->i = 50ee64
    b.i   = 0
    c->i  = 0
    
    &(as->i) = 00EFF978
    &(ar->i) = 00EFF974
    &(b.i) = 00EFF978
    &(c->i) = 00EFF978
    
    &b = 00EFF974
    as = 00EFF978
    ar = 00EFF974
    c  = 00EFF974
    Press ENTER to exit.
    

    It can be seen that the B object is built in memory as B-specific data first, followed by the embedded A object. The static_cast correctly returns the address of the embedded A object, and the pointer created by static_cast correctly gives the value of the data field. The pointer generated by reinterpret_cast treats b's memory location as if it were a plain A object, and so when the pointer tries to get the data field it returns some B-specific data as if it were the contents of this field.

    One use of reinterpret_cast is to convert a pointer to an unsigned integer (when pointers and unsigned integers are the same size):

    int i; unsigned int u = reinterpret_cast(&i);

提交回复
热议问题