平常真的很少用union 所以当要用的时候还是查了一下
https://en.cppreference.com/w/cpp/language/union
S s = {0x12345678}; // initializes the first member, s.n is now the active
member
// at this point, reading from s.s or s.c is undefined behavior
诶, 这不就是常看到union的标准用法吗?
于是我再找找
http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Ru-pun
恩....真的是undefined behavior.....完全颠覆我之前对union的认知
原来看到这种union { struct{} , array;} 全部都是UB...
想问一下
1. 即使他是 书本上的UB 但是不是可以说 所有已知compiler实作上都让他效果一致
也就是常用的那套手段也没什么问题, 真的这样写 也不用太苛责?
2. 如果真的不想写出UB 的程式码, 是不是只能用reinterpret_cast
例如
union Endian{
int a;
char b;
};
改用
int a = 1; char b = *(reinterpret_cast<char*>(&a));
对于reinterpret_cast每当用 都很怕是UB,
有没有什么通则可以快速确认是否转型是UB呢?
以上 (今天才知道union 这样写是UB, 实在很震惊)