Does the following program violate the strict aliasing rule?
#include <cstdint>
int main()
{
double d = 0.1;
//std::int64_t n = *reinterpret_cast<std::int64_t*>(&d); // aliasing violation
//auto n{*reinterpret_cast<std::int64_t*>(&d)}; // aliasing violation
auto nptr{reinterpret_cast<std::int64_t*>(&d)};
auto& n{*nptr};
++n;
}
Does the following program violate the strict aliasing rule?
Yes, it does. You are dereferencing a double*
(&d
) using a std::int64_t*
.
The line that violates strict aliasing rule is:
auto& n{*nptr};
While processing the line, the compilers don't necessarily know how you set the value of nptr
. The fact that it is an alias to a double*
is not obvious while processing that line.