Difference in behavior while using dynamic_cast with reference and pointers(使用带有引用和指针的 dynamic_cast 时的行为差异)
问题描述
我正在检查 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
";
}
//Using pointer
try
{
B* pB = dynamic_cast<B*>(p);
if( pB == NULL)
{
std::cout<<"NULL Pointer
";
}
}
catch(std::bad_cast exp)
{
std::cout<<"Caught bad cast
";
}
return 0;
}
输出是Caught bad cast"和NULL pointer".代码使用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 时的行为差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用带有引用和指针的 dynamic_cast 时的行为差异
- 静态初始化顺序失败 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- C++ 协变模板 2021-01-01
- 从python回调到c++的选项 2022-11-16
- Stroustrup 的 Simple_window.h 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01