平常真的很少用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, 实在很震惊)
你的认知应该是从 C 语言来的, 所谓的 active member就是已经建构好的物件, 如果你要改用另外一个物件就必须要先解构当前的 active member 再去建构另一个,在 C++ 里所有物件都要经过建构才能用, 只有将指标转型无视这个规则的都是 UB对于 non-class object 也是同理, 建构子/解构子一整套流程缺一不可如果懒得自己处理就改用 std::variant 吧