当目标指针不是基类的类型时,为什么允许dynamic_cast为多态类产生一个空指针? [英] Why is the dynamic_cast allowed to yield a null-pointer for polymorphic classes when the destination pointer is not of the type of a base class?

查看:160
本文介绍了当目标指针不是基类的类型时,为什么允许dynamic_cast为多态类产生一个空指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下程序

#include <iostream>
#include <iomanip>

struct A
{
};

struct C
{
};

int main()
{
    C *pc = nullptr;

    A *pa1 = dynamic_cast<A *>( pc );

    std::cout << "pa1 == nullptr is " << std::boolalpha << ( pa1 == nullptr ) << '\n';

    A *pa2 = pc;

    std::cout << "pa2 == nullptr is " << std::boolalpha << ( pa2 == nullptr ) << '\n';
}

对于两个指针声明pa1和pa2,编译器都会报告错误,表明不允许进行此类初始化.

For the both pointer declarations, pa1 and pa2, the compiler reports an error that such an initialization is not allowed.

例如,clang HEAD 10.0.0编译器会发出以下错误.

For example the clang HEAD 10.0.0 compiler issues the following errors.

prog.cc:19:14: error: 'C' is not polymorphic
    A *pa1 = dynamic_cast<A *>( pc );
             ^                  ~~
prog.cc:23:8: error: cannot initialize a variable of type 'A *' with an lvalue of type 'C *'
    A *pa2 = pc;
       ^     ~~
2 errors generated.

现在让我们将C类设为多态类.

Now let's make the class C a polymorphic class.

#include <iostream>
#include <iomanip>

struct A
{
};

struct C
{
    virtual ~C() = default; 
};


int main()
{
    C *pc = nullptr;

    A *pa1 = dynamic_cast<A *>( pc );

    std::cout << "pa1 == nullptr is " << std::boolalpha << ( pa1 == nullptr ) << '\n';

    A *pa2 = pc;

    std::cout << "pa2 == nullptr is " << std::boolalpha << ( pa2 == nullptr ) << '\n';
}

只有第二个声明会产生错误. dynamic_cast有效.

And only the second declaration produces an error. The dynamic_cast works.

rog.cc:22:8: error: cannot initialize a variable of type 'A *' with an lvalue of type 'C *'
    A *pa2 = pc;
       ^     ~~
1 error generated.

允许dynamic_cast这样的指针转换的原因是什么?

What is the reason of that such a conversion of pointers for the dynamic_cast is allowed?

推荐答案

允许dynamic_cast这样的指针转换的原因是什么?

What is the reason of that such a conversion of pointers for the dynamic_cast is allowed?

由于dynamic_cast在运行时运行,因此此时发出编译器错误为时已晚.

Because dynamic_cast runs at run time, and it's too late to issue a compiler error by then.

如果转换失败,则dynamic_cast返回nullptr.您需要检查一下,然后在需要时进行处理.

If the conversion fails, dynamic_cast returns nullptr. You need to check for that and then handle that if needed.

这篇关于当目标指针不是基类的类型时,为什么允许dynamic_cast为多态类产生一个空指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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