When I compile this sample code using g++, I get this warning:
warning: dereferencing type-punned pointer will break strict-aliasing rules
[-Wstrict-aliasing]
The code:
#include <iostream>
int main()
{
alignas(int) char data[sizeof(int)];
int *myInt = new (data) int;
*myInt = 34;
std::cout << *reinterpret_cast<int*>(data);
}
In this case, doesn't data
alias an int, and therefore casting it back to an int would not violate strict aliasing rules? Or am I missing something here?
Edit: Strange, when I define data
like this:
alignas(int) char* data = new char[sizeof(int)];
The compiler warning goes away. Does the stack allocation make a difference with strict aliasing? Does the fact that it's a char[]
and not a char*
mean it can't actually alias any type?
data
is already an alias for&data[0]
? Alsoint const * data;
is a closer match toint data[1];
– Varnerstd::aligned_storage
for this: en.cppreference.com/w/cpp/types/aligned_storage – Szombathely#pragma pack(1)
to give everything an alignment of 1, but that may give me some more freedom – Phenomenology