dou*_*lep 8 c++ generics strict-aliasing reinterpret-cast type-punning
我有一个问题,破坏了严格的指针别名规则.我有一个T来自模板的类型和一些Int相同大小的整数类型(如同sizeof).我的代码基本上做了以下事情:
T x = some_other_t;
if (*reinterpret_cast <Int*> (&x) == 0)
...
Run Code Online (Sandbox Code Playgroud)
因为T是一些可以有构造函数的任意(除了大小限制)类型,我不能建立T和的联合Int.(这仅在C++ 0x中允许,甚至GCC也不支持).
有没有什么办法可以重写上面的伪代码来保留功能并避免破坏严格的别名规则?注意,这是一个模板,我无法控制T或重视some_other_t; 赋值和后续比较确实发生在模板化代码中.
(对于记录,如果T包含任何位字段,上面的代码在GCC 4.5上开始打破.)
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))
...
Run Code Online (Sandbox Code Playgroud)
在我的系统上,GCC 优化掉了is_T_0()和memcpy(),从而在myfunc().
| 归档时间: |
|
| 查看次数: |
770 次 |
| 最近记录: |