问题描述
我正在检查dynamic_cast的行为,发现当它失败时,std :: bad_cast异常只会在目标是引用类型时抛出。如果目标是一个指针类型,那么抛出的异常不会抛出。这是我的示例代码:
I was checking the behavior of dynamic_cast and found that when it fails, std::bad_cast exception is thrown only if the destination is a reference type. If the destination is a pointer type then no exception is thrown from the cast. This is my sample code:
class A
{
public:
virtual ~A()
{
}
};
class B : public A
{
};
int main()
{
A* p = new A;
//Using reference
try
{
B& b = dynamic_cast<B&>(*p);
}
catch(std::bad_cast exp)
{
std::cout<<"Caught bad cast\n";
}
//Using pointer
try
{
B* pB = dynamic_cast<B*>(p);
if( pB == NULL)
{
std::cout<<"NULL Pointer\n";
}
}
catch(std::bad_cast exp)
{
std::cout<<"Caught bad cast\n";
}
return 0;
}
输出为陷入错误转换和NULL指针。代码是使用VS2008编译的。这是正确的行为吗?如果是,那为什么有区别?
Output is "Caught bad cast" and "NULL pointer". Code is compiled using VS2008. Is this the correct behavior ? If yes, then why there is a difference?
推荐答案
是的,这是正确的行为。原因是你可以有一个空指针,而不是一个空引用 - 任何引用必须绑定到一个对象。
Yes, this is correct behaviour. The reason is that you can have a null pointer, but not a null reference - any reference has to be bound to an object.
所以当dynamic_cast的指针类型失败它返回一个空指针,调用者可以检查它,但是当它失败的引用类型,它不能返回一个空引用,所以一个异常是唯一合理的方式来表示一个问题。
So when dynamic_cast for a pointer type fails it returns a null pointer and the caller can check for that, but when it fails for a reference type it can't return a null reference, so an exception is the only reasonable way to signal a problem.
这篇关于使用dynamic_cast与引用和指针时的行为差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!