ple*_* me 1 c++ unsigned signed casting unsafe
这样安全吗:
int main()
{
boost::int16_t t1 = 50000; // overflow here.
boost::uint16_t t2 = (boost::uint16_t)t1;
std::cout << t1 << " " << t2 << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
更具体一点:我将这些数据存储在一个表中,该表在模式中使用了签名类型,是否可以安全存储,并以这种方式检索这些数据?
谢谢!
不,我相信这是实施定义的.来自C++草案标准,§4.7/ 3
如果目标类型是有符号的,如果它可以在目标类型(和位域宽度)中表示,则该值不变; 否则,该值是实现定义的.
这适用于第一个声明. int16_t签名,它不能代表50000.所以价值t1取决于实施.
一旦你知道t1,t2§4.7/ 2保证是最低的uint16_t全等模数2 ^ 16到t1.基本上,t1mod 2 ^ 16.