简体   繁体   English

这段代码打破了严格的别名规则?

[英]This piece of code breaks strict aliasing rule?

I read http://blog.qt.digia.com/blog/2011/06/10/type-punning-and-strict-aliasing/ , and found this piece of code. 我阅读了http://blog.qt.digia.com/blog/2011/06/10/type-punning-and-strict-aliasing/ ,发现了这段代码。

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. 作者声称MSVC优化了我觉得很奇怪的任务。

Does MSVC really exploit strict aliasing rule? MSVC真的利用严格的别名规则吗?

And isn't uchar* specially allowed to be used to do type punning? 是不是uchar *特别允许用来做打字?

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. “严格别名规则”允许使用字符类型访问i引用的对象,而不管该对象的实际类型是什么。 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. 调用此方法的代码实际上甚至不必传递对与qint16兼容的对象的引用,以使此函数具有已定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM