严格的指针别名:针对特定问题的任何解决方案? [英] Strict pointer aliasing: any solution for a specific problem?
问题描述
我有一个问题是由于打破了严格的指针别名规则。我有一个类型 T
来自一个模板和一些相同大小的整型的sizeof
)。我的代码基本上完成以下工作:
T x = some_other_t;
if(* reinterpret_cast< Int *>(& x)== 0)
...
由于 T
是一些可能有构造函数的任意类型的约束(除了大小限制),所以我不能将 T
和 Int
。 (这只允许在C ++ 0x中使用,甚至还没有被GCC支持)。
有什么方法可以重写上面的伪代码来保留功能并避免打破严格的锯齿规则?请注意,这是一个模板,我无法控制 T
或 some_other_t
的值。这个赋值和随后的比较确实发生在模板代码中。
(有关记录,如果 )
{
int p;
memcpy(& p,ob,sizeof(int));
返回p == 0;
}
void myfunc(void)
{
T x = some_other_t;
if(is_T_0(& x))
...
开我的系统中,GCC优化了 is_T_0()
和 memcpy()
,结果在 myfunc()
。
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.)
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()
.
这篇关于严格的指针别名:针对特定问题的任何解决方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!