I read https://www.qt.io/blog/2011/06/10/type-punning-and-strict-aliasing, and found this piece of code.
QDataStream &QDataStream::operator>>(qint16 &i)
{
...
register uchar *p = (uchar *)(&i);
char b[2];
if (dev->read(b, 2) == 2) {
*p++ = b[1];
*p = b[0];
...
The author claims MSVC optimizes away the assignments which I find quite strange.
Does MSVC really exploit strict aliasing rule?
And isn't uchar* specially allowed to be used to do type punning?
It was either a compiler bug or a bug in the code that called this method. The "strict aliasing rule" allows the object i
refers to be accessed using character types, regardless of what the type of that object actually is. The code that calls this method doesn't even actually have to pass an reference to an object that's compatible with qint16
for this function to have defined behaviour.
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