is bit_cast without compiler support for constexpr memcpy possible?

[亡魂溺海] 提交于 2019-12-06 14:54:51

One of the things you're not allowed to do during constant evaluation is, from [expr.const]/4.9:

an lvalue-to-rvalue conversion that is applied to a glvalue that refers to a non-active member of a union or a subobject thereof;

Which is what your implementation does, so it's not a viable implementation strategy.

Volatile members are used here to force the compiler to emit the necessary code

If you need to write volatile to make sure the compiler doesn't optimize out your code then your code is not ok. A compiler cannot modify the observable behavior of a valid code. If what you wanted to do (sans volatile) would have been defined behavior, the compiler would not have been allowed to optimize out the writes and reads you want to force with volatile.

The UB comes from the fact that you are only allowed to read the active member of an union (in in your example) but you read the inactive one (out in your example).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!