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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…