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

static_cast可以在C中抛出异常吗?

发布时间:2020-12-16 05:22:38 所属栏目:百科 来源:网络整理
导读:假设static_cast永远不会抛出异常是安全的吗? 对于int到枚举转换,即使无效,也不会抛出异常.我可以依靠这种行为吗?以下代码工作. enum animal { CAT = 1,DOG = 2};int y = 10;animal x = static_castanimal(y); 解决方法 对于这种特殊类型的cast(枚举类型的
假设static_cast永远不会抛出异常是安全的吗?

对于int到枚举转换,即使无效,也不会抛出异常.我可以依靠这种行为吗?以下代码工作.

enum animal {
  CAT = 1,DOG = 2
};

int y = 10;
animal x = static_cast<animal>(y);

解决方法

对于这种特殊类型的cast(枚举类型的整数),不会抛出异常.

C++ standard 5.2.9 Static cast [expr.static.cast] paragraph 7

A value of integral or enumeration type can be explicitly converted to
an enumeration type. The value is unchanged if the original value is
within the range of the enumeration values (7.2). Otherwise,the
resulting enumeration value is unspecified.

但是,请注意,某些源/目标类型组合实际上会导致未定义的行为,这可能包括抛出异常.

换句话说,static_cast从一个整数获取枚举值的具体用法是很好的,但确保整数通过某种输入验证过程来实际表示一个有效的枚举值.

有时,输入验证过程完全不需要static_cast,就像这样:

animal GetAnimal(int y)
{
    switch(y)
    {
    case 1:
        return CAT;
    case 2:
        return DOG;
    default:
        // Do something about the invalid parameter,like throw an exception,// write to a log file,or assert() it.
    }
}

请考虑使用类似上述结构的东西,因为它不需要任何投射,并为您提供正确处理边界情况的机会.

(编辑:李大同)

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

    推荐文章
      热点阅读