加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 当dynamic_cast会抛出异常使用指针的情况?

发布时间:2020-12-16 03:21:23 所属栏目:百科 来源:网络整理
导读:我在源代码中使用dynamic_cast来将指针转换为下面的一些东西, Base *base = here storing the pointer;Derived *derived = dynamic_castDerived*(base); 在base的情况下,没有类层次结构的指针,所以cast失败并返回NULL.接下来我检查NULL.所以没有问题. 我碰到
我在源代码中使用dynamic_cast来将指针转换为下面的一些东西,
Base *base = here storing the pointer;

Derived *derived = dynamic_cast<Derived*>(base);

在base的情况下,没有类层次结构的指针,所以cast失败并返回NULL.接下来我检查NULL.所以没有问题.

我碰到一个崩溃转储,由于dynamic_cast抛出异常,我的应用程序崩溃了.

我知道dynamic_cast只有在与引用类型一起使用时才会抛出.

任何想法当dynamic_cast可以抛出异常使用指针,因为我在上面的源代码?

解决方法

Any idea when the dynamic_cast can throw exception when used with pointer as I used in above source?

在一个定义明确的程序中,它不能.该标准不允许:

[C++11: 5.2.7/9]: The value of a failed cast to pointer type is the null pointer value of the required result type. A failed cast to reference type throws std::bad_cast (18.7.2).

但是,如果您将dynamic_cast传递给无效指针,则调用未定义的行为,并且可能会发生任何事情,包括某些实现定义的C异常或运行时崩溃.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读