我有一个uint64_t
整数,并通过以下代码将最后一个32位提取为uint32_t
个数字:
uint32_t getLast(uint64_t v){
uint64_t t= v >> 32;
return reinterpret_cast<uint32_t &>( t ); // type-punned pointer warning
}
int main()
{
uint64_t a = 1l << 33 | 1l << 3;
std::cout << getLast(a) << std::endl; // prints 2
}
此代码提供警告:
warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
return reinterpret_cast<uint32_t &>( t );
我想解决这个问题,但不是使用联合类型。
reinterprete_cast
在访问数据时会给出未定义的行为(将重新解释的内容复制到返回值中)(我认为?)
另一个似乎有用的解决方案?
uint32_t getLast(uint64_t v){
return (v >> 32) // conversion from bitshifted 64bit to 32bit, but what is with overflow?
}
我有点困惑,关于reinterpret_cast的未定义行为?
那么我应该如何使用reinterpret_cast
,我认为这个例子是典型的使用模式?第二种方法也能安全地运作吗?
答案 0 :(得分:4)
你应该Retry<EndpointNotFoundException>.Do(() => SomeFunctionThatCanFail(), TimeSpan.FromSeconds(1));
。 static_cast<uint32_t>
几乎专门用于高度狡猾且可能非法的指针转换。