dynamic_cast 以意想不到的方式成功
dynamic_cast succussful in an unexpected manner
我在玩 dynamic_cast
以了解它的用法并想出了下面提供的代码。我曾经相信 dynamic_cast<D*>(B*)
成功当且仅当:
B
是一个多态类型,即它有一个虚函数 AND
D
派生自 B
但在下面的代码中,Base
和 NonDerived
类 与上述方式无关,但 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();
}
我在玩 dynamic_cast
以了解它的用法并想出了下面提供的代码。我曾经相信 dynamic_cast<D*>(B*)
成功当且仅当:
B
是一个多态类型,即它有一个虚函数 ANDD
派生自B
但在下面的代码中,Base
和 NonDerived
类 与上述方式无关,但 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();
}