Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

This piece of code breaks strict aliasing rule?

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?

like image 878
ntysdd Avatar asked Nov 10 '22 03:11

ntysdd


1 Answers

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.

like image 142
Ross Ridge Avatar answered Nov 14 '22 22:11

Ross Ridge