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

一世执手 提交于 2019-12-02 17:15:28

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.

*((int*)buf) = 42;

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!