如何避免 C++ 中的算术溢出?

How can I avoid arithmetic overflow in 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).

seekg 期望的类型是 streampos,所以执行以下操作:

infile.seekg(static_cast<streampos>pn * sizeof(makeres));

sizeof() 是一个返回 std::size_t 的常量表达式,这意味着理想情况下,无论您将该表达式的结果与什么相乘,都应该是 std::size_t 类型。现在,你可能会得到某种 "signed-unsigned" 不匹配,因为 std::streamoff 是一个带符号的整数,这就是 seekg() 接受的参数,但你不应该真正关心它。

此外,您得到的可能不是错误,而是 C++ Core Guidelines 分析警告。假设您正在使用 Visual Studio,只需在项目属性中关闭 Enable Code Analysis on Build。反正就是很头疼。