使用带有引用和指针的 dynamic_cast 时的行为差异 [英] Difference in behavior while using dynamic_cast with reference and pointers

查看:25
本文介绍了使用带有引用和指针的 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 时的行为差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆