I am building a buffer that will be used in a class and wanted to know if the following is valid according to the C++ standard:
#include <iostream>
#include <cstdint>
int main() {
alignas(std::int32_t) char A[sizeof(std::int32_t)] = { 1, 0, 0, 0 };
std::int32_t* pA = new (&A) std::int32_t;
std::cout << *pA << std::endl;
return 0;
}
The buffer has been initialized as a char
array of 4 bytes. Would doing a placement new on top of the structure allow me to access the bits underneath as an int32_t
? Can I now access the memory space there as 4 char
s (through the buffer
object) or as 1 int32_t
(through pA
) without any violation to the standard? If not, is it possible to do some other way?
NOTE: Yes, I am aware of endianness, but in this context, endianness doesn't matter. That's a different discussion.