C++ strict-aliasing agnostic cast

眉间皱痕 提交于 2019-12-04 11:22:24

As the other answers have correctly pointed out: This is not possible as you are not allowed to access the float object through an unsigned pointer and there is no cast that will remove that rule.

So how do you work around this issue? Don't access the object through an unsigned pointer! Use a float* or char* for passing the object around, as those are the only pointer types that are allowed under strict aliasing. Then when you actually need to access the object under unsigned semantics, you do a memcpy from the float* to a local unsigned (and memcpy back once you are done). Your compiler will be smart enough to generate efficient code for this.

Note that this means that you will have float* everywhere on your interfaces instead of unsigned*. And that is exactly what makes this work: The type system is aware of the correct data types at all times. Things only start to crumble if you try to smuggle a float through the type system as an unsigned*, which you'll hopefully agree is kind of a fishy idea in the first place.

Is it a correct way to do a "nonalias_cast"?

No.

But is there any nice workaround?

Again, no.

Reason for both is simply that &f is not the address of some object of type unsigned int, and no amount of casting on the pointer is going to change that.

No, your nonalias_cast does not work, and cannot work.

Type aliasing rules are not (directly) about converting pointers. In fact, none of your conversions have undefined behaviour. The rules are about accessing an object of certain type, through a pointer of another type.

No matter how you convert the pointer, the pointed object is still a float object, and accessing it through an unsigned pointer violates type aliasing rules.


An impossible dream or an elusive reality?

In standard C++, it is impossible.

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