Il semble y avoir un accord que vous ne pouvez pas willy point de bon gré mal gré (un int *) dans un tableau char
en raison des règles d'aliasing C++.Le placement est-il légalement requis pour placer un int dans un tableau char?
De cette autre question - Generic char[] based storage and avoiding strict-aliasing related UB - il semble qu'il est autorisé à (re) utiliser le stockage grâce à un placement nouveau.
alignas(int) char buf[sizeof(int)];
void f() {
// turn the memory into an int: (??) from the POV of the abstract machine!
::new (buf) int; // is this strictly required? (aside: it's obviously a no-op)
// access storage:
*((int*)buf) = 42; // for this discussion, just assume the cast itself yields the correct pointer value
}
Alors, est le C++ juridique ci-dessus et est le placement nouveau réellement nécessaire pour la rendre légale?
Connexe: http://stackoverflow.com/questions/38862092/is-it-legal-to-alias-a-char-array-through-a-pointer-to-int –
https://godbolt.org/g/k2nVI9 –
, duper potentiel très pertinent: https://stackoverflow.com/questions/40873520/reinterpret-cast-creating-a-trivially-default-constructible-object –