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;
}
No warning emitted by VS2015, clang or gcc.
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.
Yes, this violates strict aliasing. You are accessing an object d
of type double
, though a pointer nptr
which is not a pointer to double
or any type related to it.
Just because a compiler does not emit a warning does not mean it isn't a violation. Violations of strict arising are UB (since they're a matter of runtime behavior) and therefore do not require a diagnostic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With