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 时的行为差异
基础教程推荐
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01