Is the strict aliasing rule incorrectly specified?

前端 未结 9 537
野的像风
野的像风 2020-12-29 03:50

As previously established, a union of the form

union some_union {
    type_a member_a;
    type_b member_b;
    ...
};

with n memb

9条回答
  •  有刺的猬
    2020-12-29 04:14

    Essentially the strict aliasing rule describes circumstances in which a compiler is permitted to assume (or, conversely, not permitted to assume) that two pointers of different types do not point to the same location in memory.

    On that basis, the optimisation you describe in strict_aliasing_example() is permitted because the compiler is allowed to assume f and i point to different addresses.

    The breaking_example() causes the two pointers passed to strict_aliasing_example() to point to the same address. This breaks the assumption that strict_aliasing_example() is permitted to make, therefore results in that function exhibiting undefined behaviour.

    So the compiler behaviour you describe is valid. It is the fact that breaking_example() causes the pointers passed to strict_aliasing_example() to point to the same address which causes undefined behaviour - in other words, breaking_example() breaks the assumption that the compiler is allowed to make within strict_aliasing_example().

提交回复
热议问题