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

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

假设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.
    }
}

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

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

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

相关推荐