dynamic_cast 以意想不到的方式成功

dynamic_cast succussful in an unexpected manner

我在玩 dynamic_cast 以了解它的用法并想出了下面提供的代码。我曾经相信 dynamic_cast<D*>(B*) 成功当且仅当:

但在下面的代码中,BaseNonDerived 类 与上述方式无关,但 dynamic_cast<NonDerived*>(Base*) 仍然成功。我原以为它会失败,而是 return 一个 NULL。哪个 C++ 规则在这里发挥作用?

我正在使用符合 C++11 标准的编译器。

#include <iostream>

class Base {
    public:
        virtual ~Base() = default;
};

class Derived: public Base {
    public:
        void DerivedFun(){
            std::cout << "Derived" << std::endl;
        }
};

class NonDerived{
    public:
        void NonDerivedFun(){
            std::cout << "NonDerived" << std::endl;
        }
};

int main(){
    Base *pb = new Derived();

    Derived *pd = dynamic_cast<Derived*>(pb); // Expected this to succeed and it did
    pd->DerivedFun(); // Prints "Derived" as expected

    NonDerived *pn = dynamic_cast<NonDerived*>(pb); // Expected it to fail but it succeeded?
    pn->NonDerivedFun(); // Prints "NonDerived", expected this to throw some null pointer exception!!

    delete pb;
    return 0;
}

pn->NonDerivedFun(); // Prints "NonDerived", expected this to throw some null pointer exception!!

解引用空指针时没有 "null pointer exception" 这样的东西。 undefined behavior 这样做。为了避免这种情况,您必须检查 dynamic_cast 是否成功:

if (pn != nullptr) {
    pn->NonDerivedFun();
}