Why can't static_cast be used to down-cast when virtual inheritance is involved?

后端 未结 6 786
情深已故
情深已故 2020-11-28 07:37

Consider the following code:

struct Base {};
struct Derived : public virtual Base {};

void f()
{
    Base* b = new Derived;
    Derived* d = static_cast<         


        
6条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-28 08:12

    static_cast is a compile time construct. it checks for the validity of cast at compile time and gives an compilation error if invalid cast.

    virtualism is a runtime phenomenon.

    Both can't go together.

    C++03 Standard §5.2.9/2 and §5.2.9/9 ar relevant in this case.

    An rvalue of type “pointer to cv1 B”, where B is a class type, can be converted to an rvalue of type “pointer to cv2 D”, where D is a class derived (clause 10) from B, if a valid standard conversion from “pointer to D” to “pointer to B” exists (4.10), cv2 is the same cv-qualification as, or greater cv-qualification than, cv1, and B is not a virtual base class of D. The null pointer value (4.10) is converted to the null pointer value of the destination type. If the rvalue of type “pointer to cv1 B” points to a B that is actually a sub-object of an object of type D, the resulting pointer points to the enclosing object of type D. Otherwise, the result of the cast is undefined.

提交回复
热议问题