c++ - 如何避免 C++ 中的算术溢出?
问题描述
这是我编译时有警告的代码的一部分,我不明白如何避免算术溢出问题
void read(int pn) //read person number pn
{
ifstream infile;
infile.open("data.txt", ios::binary);
infile.seekg(pn * sizeof(makers)); // this is the line I get warning
infile.read((char*)this, sizeof(*this));
}
我得到的警告:
Arithmetic overflow: Using operator '*' on a 4 byte value and then
casting the result to a 8 byte value. Cast the value to the wider
type before calling operator '*' to avoid overflow (io.2).
解决方案
sizeof()
是一个返回的常量表达式std::size_t
,这意味着理想情况下,无论您将该表达式的结果乘以什么,都应该是 type std::size_t
。现在,无论如何你可能会得到某种“有符号-无符号”不匹配,因为std::streamoff
它是一个有符号整数,这就是seekg()
作为参数接受的,但这不应该让你真正关心。
此外,您得到的可能不是错误,而是 C++ Core Guidelines 分析警告。假设您使用的是 Visual Studio,只需Enable Code Analysis on Build
在项目属性中关闭即可。无论如何,这只是一个主要的痛苦。
推荐阅读
- java - 播放框架泄漏 jar 文件导致“打开的文件过多”错误
- c++ - 计算闰年 - 表达式必须有一个可修改的左值
- c# - 带有接口列表的接口,如何选择接口实现的一种类型
- php - 在for循环中添加所有先前的数字以获取当前数字
- c++ - C++ if 语句不打印所需的输出
- c# - 对从 AutoMapper 映射的实体使用 AsNoTracking
- python - 为什么不能从我的个人 PyPI 服务器安装 Python 包?
- python - Tensorflow 数据管道:缓存到磁盘很慢 - 如何提高评估性能?
- php - 使用总计创建报告
- powerbi - Power Bi - 如何过滤和计算 52 列中的零值