Is placement new legally required for putting an int into a char array?

前端 未结 2 894
Happy的楠姐
Happy的楠姐 2021-01-31 10:51

There seems to be some agreement that you can\'t willy nilly point (an int*) into a char array because of the C++ aliasing rules.

From this other question -

相关标签:
2条回答
  • 2021-01-31 11:29
    *((int*)buf) = 42;
    

    writes an int with a int lvalue, so there is no aliasing issue in the first place.

    0 讨论(0)
  • 2021-01-31 11:30

    Yes, the placement new is necessary, otherwise you'd violate strict aliasing (assignment is access).

    Is the above legal? Almost (although it will work on virtually all implementations). The pointer you've created through the cast does not point to the object, because the (now destroyed) array and the int object are not pointer-interconvertible; use std::launder((int*)buf), or better yet, use the placement new's return value.

    0 讨论(0)
提交回复
热议问题