Does this really break strict-aliasing rules?

后端 未结 3 1739
执念已碎
执念已碎 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:51

    The warning is absolutely justified. The decayed pointer to data does not point to an object of type int, and casting it doesn't change that. See [basic.life]/7:

    If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object will automatically refer to the new object and, once the lifetime of the new object has started, can be used to manipulate the new object, if:
    (7.1) — [..]
    (7.2) — the new object is of the same type as the original object (ignoring the top-level cv-qualifiers),

    The new object is not an array of char, but an int. P0137, which formalizes the notion of pointing, adds launder:

    [ Note: If these conditions are not met, a pointer to the new object can be obtained from a pointer that represents the address of its storage by calling std::launder (18.6 [support.dynamic]). — end note ]

    I.e. your snippet can be corrected thusly:

    std::cout << *std::launder(reinterpret_cast(data));
    

    .. or just initialize a new pointer from the result of placement new, which also removes the warning.

提交回复
热议问题