☰
  • 首页
  • 规则分类
  • 项目介绍
search
•••

在 C++ 代码中不应使用宏 offsetof

3.3.6 ID_deprecatedOffsetof
目录 › next › previous

宏 offsetof 很难适用于具有 C++ 特性的类,在 C++ 代码中不应使用。

如果 offsetof 用于:

  • 非“standard-layout”类型
  • 计算静态成员或成员函数的偏移量

会导致标准未定义的行为。

示例:

struct A {
    int i;
    virtual int f();
};

int foo() {
    return offsetof(A, i);  // Non-compliant, undefined behavior
}

struct B {
    static int i;
    int f();
};

int bar() {
    return offsetof(B, i);  // Non-compliant, undefined behavior
}

int baz() {
    return offsetof(B, f);  // Non-compliant, undefined behavior
}

依据

ISO/IEC 14882:2003 18.1(5)-undefined ISO/IEC 14882:2011 18.2(4)-undefined

参考

MISRA C++ 2008 18-2-1 SEI CERT EXP59-CPP
Copyright©2024 360 Security Technology Inc., Licensed under the Apache-2.0 license.