static_cast可以在C ++中抛出异常吗? [英] Can static_cast throw an exception in C++?

查看:330
本文介绍了static_cast可以在C ++中抛出异常吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以假设static_cast永远不会抛出异常?

Is it safe to assume that static_cast will never throw an exception?

对于int到枚举类型,即使无效也不会抛出异常。我可以依靠这种行为吗?以下代码适用。

For an int to Enum cast, an exception is not thrown even if it is invalid. Can I rely on this behavior? This following code works.

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

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


推荐答案

到枚举类型),不会抛出任何异常。

For this particular type of cast (integral to enumeration type), no exception will be thrown.


C ++标准5.2.9静态强制转换static.cast]段落7

整数或枚举类型的值可以显式转换为
的枚举类型。如果原始值在枚举值(7.2)的范围内为
,则值不变。 否则,
产生的枚举值未指定

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.

目标类型组合确实会导致未定义的行为,其中可能包括抛出异常。

However, note that some source/destination type combinations do in fact result in undefined behavior, which may include throwing an exception.

换句话说, c $ c> static_cast 从一个整数获得一个枚举值是好的,但确保整数实际上代表一个有效的枚举值通过某种输入验证过程。

In other words, your particular usage of static_cast to get an enumerated value from an integer is fine, but do make sure that the integer actually represents a valid enumerated value via some kind of input validation procedure.

有时,输入验证过程完全不需要 static_cast ,如下所示:

Sometimes the input validation procedure completely eliminates the need for a static_cast, like so:

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

请考虑使用类似上述结构不需要转换,并给您正确处理边界情况的机会。

Do consider using something like the above structure, for it requires no casts and gives you the opportunity to handle boundary cases correctly.

这篇关于static_cast可以在C ++中抛出异常吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆