Should I use static_cast or reinterpret_cast when casting a void* to whatever

后端 未结 4 872
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 16:08

Both static_cast and reinterpret_cast seem to work fine for casting void* to another pointer type. Is there a good reason to favor one over the other?

4条回答
  •  没有蜡笔的小新
    2020-11-22 16:48

    My personal preference is based on code literacy like this:

    void* data = something;
    MyClass* foo = reinterpret_cast(data);
    foo->bar();
    

    or

    typedef void* hMyClass; //typedef as a handle or reference
    hMyClass = something;
    const MyClass& foo = static_cast(*hMyClass);
    foo.bar();
    

    They both do the same in the end, but static_cast seems more appropriate in a middle-ware, app enviroment, while reinterpret cast seems more like something you'd see in a lower-level library IMHO.

提交回复
热议问题