strict aliasing and alignment

前端 未结 4 1140
悲哀的现实
悲哀的现实 2020-12-05 01:10

I need a safe way to alias between arbitrary POD types, conforming to ISO-C++11 explicitly considering 3.10/10 and 3.11 of n3242 or later. There are a lot of questions about

4条回答
  •  爱一瞬间的悲伤
    2020-12-05 01:30

    My question is, just to be sure, is this program legal according to the standard?

    No. The alignment may be unnatural using the alias you have provided. The union you wrote just moves the point of the alias. It may appear to work, but that program may fail when CPU options, ABI, or compiler settings change.

    And if not, how could one modify this to be legal?

    Create natural temporary variables and treat your storage as a memory blob (moving in and out of the blob to/from temporaries), or use a union which represents all your types (remember, one active element at a time here).

提交回复
热议问题