关于c ++:Dynamic_cast不需要执行运行时检查?

Dynamic_cast not needing to perform a run-time check?

本问题已经有最佳答案,请猛点这里访问。

引用C++GOCHACS中的第45项:

First a dynamic_cast is not necessarily dynamic, in that it may not
perform a runtime check. When performing a dynamic_cast from a derived
class pointer (or reference) to one of its public base classes no
runtime check is needed, because the compiler can determine statically
that the cast will succeed. Of course, no cast of any kind is needed
in this case, since conversion from a derived class to its public base
classes is predefined.

我认为上面的描述是通常使用动态类型转换的地方(因此会执行运行时检查吗??)

有人能解释一下上面的引用和"典型"需要使用动态演员表之间的区别吗?这让我很困惑,为什么我不需要在上面的场景中使用它。


1
2
3
4
5
6
7
8
9
class Base {
public:
    virtual ~Base() {}
    // ...
};

class Derived : public Base {
    // ...
};

"典型使用":

1
2
3
4
5
6
7
8
void foo(Derived*);

void f(Base* pb)
{
    if (Derived* pd = dynamic_cast<Derived*>(pb)) {
        foo(pd);
    }
}

"以上报价":

1
2
3
4
5
6
7
8
void bar(Base*);

void f(Derived* pd)
{
    Base* pb = dynamic_cast<Base*>(pd); // the dynamic_cast is useless here
                                        //  because a Derived IS-A Base, always
    bar(pb); // Note: could as well call directly bar(pd); (implicit conversion)
}

dynamic_cast主要用于下铸和交叉铸。gotcha提到了upcast。

具有结构b1、b2、d:b1、b2:

  • 上抛:d*->b1*,d*->b2*
  • 下浇:d*<-b1*,d*<-b2*
  • 交叉转换:b1*<->b2*(如果您的最派生类是d,则可以使用)。