微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我在源代码中使用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异常或运行时崩溃.

原文地址:https://www.jb51.cc/c/111762.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐