Strict alising的坑


1

int foo(int *x, long *y) {
  *x = 0;
  *y = 1;
  return *x;
}

会被优化成

foo2:   movl    $0, (%rdi)
        xorl    %eax, %eax
        movq    $1, (%rsi)
        ret

因为编译器会认为,shttps://intmainreturn0.com/wp-admin/plugins.phptrong两个不能alising的指针,一定不会指向同一块内存区域,所以会推断出结果一定是0

所以啊,之前网上很多(float *)(&int_var)然后乱搞的做法都容易爆炸……

哪些可以aliasing

N3797, 3.10.10

— the dynamic type of the object,

— a cv-qualified version of the dynamic type of the object,

— a type similar (as defined in 4.4) to the dynamic type of the object,

— a type that is the signed or unsigned type corresponding to the dynamic type of the object,

— a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,

— an aggregate or union type that includes one of the aforementioned types among its elements or non-static data members (including, recursively, an element or non-static data member of a subaggregate or contained union),

— a type that is a (possibly cv-qualified) base class type of the dynamic type of the object,

— a char or unsigned char type.

怎么绕

union

int i;
float *pf = (float*)&i;
*pf = 0; // illegal

可以改成

union U
{
    int i;
    float f;
};

U u;
u.i = 2;
float * pf = &U.f;
*pf = 0;

char_type

int a[100];
char *pc_start = (char *)a;
for (char *pc = pc_start; pc != pc_start + sizeof(a); ++pc)
{
    // do something
} 

-fno-strict-aliasing

万不得已的做法,然而还有很多老项目在搞……

1.
    <div class="csl-right-inline">
      The Strict Aliasing Situation is Pretty Bad – Embedded in Academia. The Strict Aliasing Situation is Pretty Bad. <a href="http://blog.regehr.org/archives/1307" target="_blank">http://blog.regehr.org/archives/1307</a>. 见於 十一月 11, 2016.
    </div>
  </div>
</div>