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

后端 未结 7 1275
隐瞒了意图╮
隐瞒了意图╮ 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:36

    Don't do that at home

    struct Base {
        virtual ~Base ();
    };
    
    struct D : Base {};
    
    Base *create () {
        D *p = new D;
        return p;
    }
    
    void *destroy1 (Base *b) {
        void *p = dynamic_cast (b);
        b->~Base ();
        return p;
    }
    
    void destroy2 (void *p) {
        operator delete (p);
    }
    
    int i = (destroy2 (destroy1 (create ())), i);
    

    Warning: This will not work if D is defined as:

    struct D : Base {
        void* operator new (size_t);
        void operator delete (void*);
    };
    

    and there is no way to make it work.

提交回复
热议问题