Search code examples
c++genericsreinterpret-caststrict-aliasingtype-punning

Strict pointer aliasing: any solution for a specific problem?


I have a problem caused by breaking strict pointer aliasing rule. I have a type T that comes from a template and some integral type Int of the same size (as with sizeof). My code essentially does the following:

T x = some_other_t;
if (*reinterpret_cast <Int*> (&x) == 0)
  ...

Because T is some arbitary (other than the size restriction) type that could have a constructor, I cannot make a union of T and Int. (This is allowed only in C++0x only and isn't even supported by GCC yet).

Is there any way I could rewrite the above pseudocode to preserve functionality and avoid breaking strict aliasing rule? Note that this is a template, I cannot control T or value of some_other_t; the assignment and subsequent comparison do happen inside the templated code.

(For the record, the above code started breaking on GCC 4.5 if T contains any bit fields.)


Solution

  • static inline int is_T_0(const T *ob)
    {
            int p;
            memcpy(&p, ob, sizeof(int));
            return p == 0;
    }
    
    void myfunc(void)
    {
        T x = some_other_t;
        if (is_T_0(&x))
            ...
    

    On my system, GCC optimizes away both is_T_0() and memcpy(), resulting in just a few assembly instructions in myfunc().