When is static cast safe when you are using multiple inheritance?

前端 未结 6 608
眼角桃花
眼角桃花 2020-12-10 12:26

I found myself in a situation where I know what type something is. The Type is one of three (or more) levels of inheritance. I call factory which returns B* how

6条回答
  •  甜味超标
    2020-12-10 13:16

    The problem lies with this line:

    B*  a = (B*)cptr;
    

    If you convert something to a void pointer, you must convert it back to the same type that it was converted from first before doing any other casts. If you have a situation where multiple different types of objects have to go through the same void pointer, then you need to first cast it down to a common type before converting to a void pointer.

    int main(){
      B *bptr = new DD; // convert to common base first (won't compile in this case)
      void* cptr = bptr; // now pass it around as a void pointer
      B*  a = (B*)cptr; // now back to the type it was converted from
      D2* b = static_cast(a); // this should be ok now
      D2* c = dynamic_cast(a);  // as well as this
      std::cout << a << " " <

    EDIT: If you only know that cptr points to some object which is of a type derived from B at the time of the cast, then that isn't enough information to go on. The compiler lets you know that when you try to convert the DD pointer to a B pointer.

    What you would have to do is something like this:

    int main(){
      void* cptr = new DD; // convert to void *
      DD* a = (DD*)cptr; // now back to the type it was converted from
      D2* b = static_cast(a); // this should be ok now, but the cast is unnecessary
      D2* c = dynamic_cast(a);  // as well as this
      std::cout << a << " " <

    but I'm not sure if that is acceptable in your actual usage.

提交回复
热议问题