Should static_cast<Derived *>(Base pointer) give compile time error?

心已入冬 提交于 2019-12-17 18:52:28

问题


Should static_cast(Base pointer) give compile time error?

class A
{
public:
    A()
    {

    }
};

class B : public  A
{
 public:
     B()
     {
     }
};

int main()
{
    A *a=new A();
    B * b=static_cast<B*>(a);   // Compile Error?
}

回答1:


It cannot give compile time error because a Base-Derived relationship can exist at runtime depending on the address of the pointers being casted. static_cast always succeeds, but will raise undefined-behavior if you don't cast to the right type. dynamic_cast may fail or not, actually telling you whether you tried to cast to the right type or not.

So in my opinion, static_cast should be used to downcast only if the design can establish that such a possibility exists. One good example of this is CRTP. So it is logical in some situations but try to avoid it as it is undefined-behavior.

RTTI is not needed for static_cast which might make it theoretically faster, but I will anytime trade-in a dynamic_cast against the undefined behavior that static_cast may cause!




回答2:


It doesn't give a compile time error because the cast could very-well be valid, and you would often do it in practice, e.g.:

A* a = new B;
B* b = static_cast<B*>(a); // OK

In your code, as far as the compiler is concerned, you are doing the same thing. It cannot know that the cast would be invalid, so it allows it at compile time. At run time however, you're going to get some nasty errors as soon as you try to use a feature of B on an instance of A.



来源:https://stackoverflow.com/questions/2469013/should-static-castderived-base-pointer-give-compile-time-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!