如果static_cast< Derived *>(基本指针)给出编译时错误? [英] Should static_cast<Derived *>(Base pointer) give compile time error?

查看:195
本文介绍了如果static_cast< Derived *>(基本指针)给出编译时错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果static_cast(基本指针)给出编译时错误?

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?
}


推荐答案

因为基于派生的关系可以在运行时存在,这取决于被转换的指针的地址。
static_cast 总是成功,但如果您未投放到正确的类型,则会产生未定义行为 dynamic_cast 可能会失败或失败,实际上告诉您是否尝试投放到正确的类型。

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.

在我看来, static_cast 应该用于 downcast ,只有当设计可以确定存在这样的可能性。一个很好的例子是 CRTP 。所以在某些情况下是合乎逻辑的,但是尽量避免它,因为它是未定义的行为。

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.

static_cast 不需要RTTI,这可能会使理论上更快将随时对 static_cast 可能导致的未定义行为交易 dynamic_cast

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!

这篇关于如果static_cast&lt; Derived *&gt;(基本指针)给出编译时错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆