C++ strict aliasing when not using pointer returned by placement new

后端 未结 2 1042
我在风中等你
我在风中等你 2021-02-15 19:07

Can this potentially cause undefined behaviour?

uint8_t storage[4];

// We assume storage is properly aligned here.
int32_t* intPtr = new((void*)storage) int32_t         


        
2条回答
  •  终归单人心
    2021-02-15 19:24

    The pointer returned by placement new can be just as UB-causing as any other pointer when aliasing considerations are brought into it. It's your responsibility to ensure that the memory you placed the object into isn't aliased by anything it shouldn't be.

    In this case, you cannot assume that uint8_t is an alias for char and therefore has the special aliasing rules applied. In addition, it would be fairly pointless to use an array of uint8_t rather than char because sizeof() is in terms of char, not uint8_t. You'd have to compute the size yourself.

    In addition, reinterpret_cast's effect is entirely implementation-defined, so the code certainly does not have a well-defined meaning.

    To implement low-level unpleasant memory hacks, the original memory needs to be only aliased by char*, void*, and T*, where T is the final destination type- in this case int, plus whatever else you can get from a T*, such as if T is a derived class and you convert that derived class pointer to a pointer to base. Anything else violates strict aliasing and hello nasal demons.

提交回复
热议问题