编译器警告(错误)C4597

未定义的行为:offsetof 应用于虚拟基础的成员

使用 offsetof(T, m)(其中 m 表示静态数据成员或成员函数)会导致出现 C4597。

备注

此警告是 Visual Studio 2017 版本 15.3 中的新增功能。 默认情况下,报告为错误。 有关如何按编译器版本禁用警告的信息,请参阅由编译器版本引发的编译器警告

示例

以下代码生成错误 C4597:

#include <cstddef>

struct A {
   int ten() { return 10; }
   static constexpr int two = 2;
};

constexpr auto off = offsetof(A, ten);  // C4597: undefined behavior: offsetof applied to member function 'A::ten'
constexpr auto off2 = offsetof(A, two); // C4597: undefined behavior: offsetof applied to static data member 'A::two'

此代码格式错误,可能会导致运行时发生故障。 若要修复此错误,请更改代码:不要对成员函数或静态数据成员调用 offsetof。 这是 C++ 标准不允许使用的不可移植代码。