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

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

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...