Home >Backend Development >C++ >When Must Placement-New Be Used with `reinterpret_cast` to Create Trivially Default-Constructible Objects?
Reinterpret_cast and the Creation of Trivially Default-Constructible Objects
cppreference used to claim that reinterpret_cast could be used to create trivially default-constructible objects on suitably aligned storage. However, this claim has since been corrected to state that placement-new is required in such cases to formally introduce an object and avoid undefined behavior.
When Does Object Lifetime Begin?
Given this correction, it is clear that no X object exists in the code provided. Therefore, any attempt to access its members (e.g., reinterpret_cast
The Role of alignas()
The alignas() specifier ensures that the storage is suitably aligned to hold an X. It does not create an X object. If there were a branch between the alignas() declaration and the reinterpret_cast, it would not change the fact that no X object exists.
Changes in C Standards
The interpretation of this behavior has remained consistent between C 11 and C 1z. The concept of creating objects without explicit construction through reinterpret_cast is not supported in either standard.
The above is the detailed content of When Must Placement-New Be Used with `reinterpret_cast` to Create Trivially Default-Constructible Objects?. For more information, please follow other related articles on the PHP Chinese website!