平常真的很少用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, 實在很震驚)