編譯器警告 (錯誤) C4597

未定義的行為: offsetof 套用至虛擬基底的成員

使用 offsetof(T, m) where 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++ 標準不允許的程式碼。