使用带有引用和指针的 dynamic_cast 时的行为差异

2021-12-31 00:00:00 casting c++ 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.

相关文章