Compiler Warning (error) C4597
undefined behavior:
offsetof
applied to a member of a virtual base
Using offsetof(T, m)
where m
refers to a static data member or a member function results in C4597.
Remarks
This warning is new in Visual Studio 2017 version 15.3. It's reported as an error by default. For information on how to disable warnings by compiler version, see Compiler warnings by compiler version.
Example
The following code produces error 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'
This code is ill-formed and could potentially cause a crash at runtime. To fix the error, change the code: don't invoke offsetof
on member functions or static data members. It's non-portable code that's disallowed by the C++ standard.