Strict pointer aliasing: is access through a 'volatile' pointer/reference a solution?

后端 未结 2 965
[愿得一人]
[愿得一人] 2020-12-09 12:41

On the heels of a specific problem, a self-answer and comments to it, I\'d like to understand if it is a proper solution, workaround/hack or just plain wrong.

Specif

2条回答
  •  一生所求
    2020-12-09 13:33

    Volatile can't help you avoid undefined behaviour here. So, if it works for you with GCC it's luck.

    Let's assume T is a POD. Then, the proper way to do this is

    T x = …;
    int i;
    memcpy(&i,&x,sizeof i);
    if (i==0)
      …
    

    There! No strict aliasing problem and no memory alignment problem. GCC even handles memcpy as an intrinsic function (no function call is inserted in this case).

提交回复
热议问题