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?
The warning is absolutely justified. The decayed pointer to
data
does not point to an object of typeint
, and casting it doesn't change that. See [basic.life]/7:The new object is not an array of
char
, but anint
. P0137, which formalizes the notion of pointing, addslaunder
:I.e. your snippet can be corrected thusly:
.. or just initialize a new pointer from the result of placement new, which also removes the warning.