Are there practical uses for dynamic-casting to void pointer?

后端 未结 7 1240
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 14:00

In C++, the T q = dynamic_cast(p); construction performs a runtime cast of a pointer p to some other pointer type T that must

相关标签:
7条回答
  • 2020-11-27 14:52

    Bear in mind that C++ lets you do things the old C way.

    Suppose I have some API in which I'm forced to smuggle an object pointer through the type void*, but where the callback it's eventually passed to will know its dynamic type:

    struct BaseClass {
        typedef void(*callback_type)(void*);
        virtual callback_type get_callback(void) = 0;
        virtual ~BaseClass() {}
    };
    
    struct ActualType: BaseClass {
        callback_type get_callback(void) { return my_callback; }
    
        static void my_callback(void *p) {
            ActualType *self = static_cast<ActualType*>(p);
            ...
        }
    };
    
    void register_callback(BaseClass *p) {
       // service.register_listener(p->get_callback(), p); // WRONG!
       service.register_listener(p->get_callback(), dynamic_cast<void*>(p));
    }
    

    The WRONG! code is wrong because it fails in the presence of multiple inheritance (and isn't guaranteed to work in the absence, either).

    Of course, the API isn't very C++-style, and even the "right" code can go wrong if I inherit from ActualType. So I wouldn't claim that this is a brilliant use of dynamic_cast<void*>, but it's a use.

    0 讨论(0)
提交回复
热议问题