When to use reinterpret_cast?

前端 未结 11 1223
我寻月下人不归
我寻月下人不归 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:38

    One case when reinterpret_cast is necessary is when interfacing with opaque data types. This occurs frequently in vendor APIs over which the programmer has no control. Here's a contrived example where a vendor provides an API for storing and retrieving arbitrary global data:

    // vendor.hpp
    typedef struct _Opaque * VendorGlobalUserData;
    void VendorSetUserData(VendorGlobalUserData p);
    VendorGlobalUserData VendorGetUserData();
    

    To use this API, the programmer must cast their data to VendorGlobalUserData and back again. static_cast won't work, one must use reinterpret_cast:

    // main.cpp
    #include "vendor.hpp"
    #include 
    using namespace std;
    
    struct MyUserData {
        MyUserData() : m(42) {}
        int m;
    };
    
    int main() {
        MyUserData u;
    
            // store global data
        VendorGlobalUserData d1;
    //  d1 = &u;                                          // compile error
    //  d1 = static_cast(&u);       // compile error
        d1 = reinterpret_cast(&u);  // ok
        VendorSetUserData(d1);
    
            // do other stuff...
    
            // retrieve global data
        VendorGlobalUserData d2 = VendorGetUserData();
        MyUserData * p = 0;
    //  p = d2;                                           // compile error
    //  p = static_cast(d2);                // compile error
        p = reinterpret_cast(d2);           // ok
    
        if (p) { cout << p->m << endl; }
        return 0;
    }
    

    Below is a contrived implementation of the sample API:

    // vendor.cpp
    static VendorGlobalUserData g = 0;
    void VendorSetUserData(VendorGlobalUserData p) { g = p; }
    VendorGlobalUserData VendorGetUserData() { return g; }
    

提交回复
热议问题