Does this really break strict-aliasing rules?

后端 未结 3 1738
执念已碎
执念已碎 2020-11-29 06:09

When I compile this sample code using g++, I get this warning:

warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wst

3条回答
  •  醉梦人生
    2020-11-29 06:58

    *myInt = 34; this expression is well-formed, because data provide storage for object of type int and myInt is a pointer to an object of type int. So, dereference such a pointer can access an object of type int.

    For *reinterpret_cast(data); this expression, it would violate the strict pointer aliasing. Firstly, there's an array-to-pointer conversion that applied to data, The result is a pointer to the initial element of data,it means the operand of reinterpret_cast is a pointer to a subject of data.
    According to the following rule:

    If an object is created in storage associated with a member subobject or array element e, the created object is a subobject of e's containing object if:

    • the lifetime of e's containing object has begun and not ended, and
    • the storage for the new object exactly overlays the storage location associated with e, and
    • the new object is of the same type as e (ignoring cv-qualification).

    An object of type int satisfy none of these rules. Hence, the operand of reinterpret_cast is not a pointer to an object that pointer-interconvertible with an object of type int. So, The result of reinterpret_cast is not an pointer to an object of type int.

    a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:

    • the dynamic type of the object.
    • [...]

提交回复
热议问题