C++int枚举类UB
我有一个enum看起来像这样:
enum class MY_TYPE : int32_t{
UNKNOWN = 0,
A = 101,
B = 102,
C = 103,
D = 104,
E = 105
};
我想从和向它投射给定的值。
首先,能不能保证下面的代码不会诱发未定义的行为?
int32_t library_func(int* tp){ *tp = 275; return 0;}
int main(){
MY_TYPE d = static_cast<MY_TYPE>(224);
library_func(reinterpret_cast<int*>(&d));
std::cout << "d is " << static_cast<int>(d);
}
如果我投射的值不在 的值范围内,它是 UBMY_TYPE吗?关于这一点,我发现了以下问题:如果您向枚举类 static_cast 无效值会发生什么?
This prints 275 as expected. Do I understand the answer correctly that casting any value which fits in the enum's underlying type is fine?
回答
Interestingly enough, UB in the example provided is strictly related to the aliasing by pointer, and not assigning enum to value which is not named. If it would not be aliasing by pointer, there would be no UB with using value outside of the enum, i.e. following is A-OK:
int32_t library_func(int32_t tp){ return tp * 10;}
int main(){
MY_TYPE d = static_cast<MY_TYPE>(224);
MY_TYPE v {library_func(static_cast<int32_t>(d))};
std::cout << "v is " << static_cast<int32_t>(v);
}