gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 15:35:54 34 4
gpt4 key购买 nike

假设 static_cast 永远不会抛出异常是否安全?

对于 int 到 Enum 的转换,即使无效也不会抛出异常。我可以依赖这种行为吗?以下代码有效。

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

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

最佳答案

对于这种特定类型的转换(枚举类型的组成部分),可能会抛出异常。

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 / undefined (since C++17).

请注意,自 C++17 以来,此类转换实际上可能会导致未定义的行为,这可能包括抛出异常。

换句话说,如果您确保整数实际上代表一个有效的枚举值,那么您使用 static_cast 从整数中获取枚举值的特定用法在 C++17 之前是可以的,并且总是可以的通过某种输入验证程序的值。

有时输入验证程序完全不需要 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++ - static_cast 可以在 C++ 中抛出异常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11551853/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com