Conversion from void* to the pointer of the base class

前端 未结 4 1977
时光取名叫无心
时光取名叫无心 2020-12-05 21:01

I have some hierarchy: base, derived classes and some structure storing user data as void*. That void can store both Base and Derived classes pointers. Main problem that I d

4条回答
  •  盖世英雄少女心
    2020-12-05 21:35

    void*'s can only be converted back to their original type. When you store a Derived* in a void*, you can only cast back to Derived*, not Base*.

    This is especially noticeable with multiple inheritance, as your derived object might not necessarily be at the same address as your base. If you really need to store things (and retrieve things) with void*, always cast to the base type first, so you have a stable way of getting the object back:

    #include 
    
    struct base { int type; };
    struct intruder { int iminyourclassstealingyourbase; };
    struct derived : intruder, base {};
    
    int main()
    {
        derived d; d.type = 5;
    
        void* good = (base*)&d;
        void* bad = &d;
    
        base* b1 = (base*)good;
        base* b2 = (base*)bad;
    
        std::cout << "good: " << b1->type << "\n";
        std::cout << "bad: " << b2->type << "\n";
    }
    

    If you then want to go back to the derived type, use a dynamic_cast (or static_cast if you're guaranteed it has to be of the derived type.)

提交回复
热议问题