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

后端 未结 2 961
[愿得一人]
[愿得一人] 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).

    0 讨论(0)
  • 2020-12-09 13:33

    Volatile can't help you avoid undefined behaviour here.

    Well, anything regarding volatile is somewhat unclear in the standard. I mostly agreed with your answer, but now I would like to slightly disagree.

    In order to understand what volatile means, the standard is not clear for most people, notably some compiler writers. It is better to think: when using volatile (and only when), C/C++ is pretty much high level assembly.

    When writing to a volatile lvalue, the compiler will issue a STORE, or multiple STORE if one is not enough (volatile does not imply atomic).

    When writing to a volatile lvalue, the compiler will issue a LOAD, or multiple LOAD if one is not enough.

    Of course, where there is no explicit LOAD or STORE, the compiler will just issue instructions which imply a LOAD or STORE.

    sellibitze gave the best solution: use memcpy for bit reinterpretations.

    But if all accesses to a memory region are done with volatile lvalues, it is perfectly clear that the strict aliasing rules do not apply. This is the answer to your question.

    0 讨论(0)
提交回复
热议问题