在C++中__builtin_offsetof运算符(或Symbian中的_FOFF运算符)的作用是什么?

此外,它还返回什么?指针?字节数?

最佳答案

它是GCC编译器提供的内置函数,用于实现C和C++标准指定的offsetof宏:

GCC - offsetof

它以字节为单位返回POD struct/union成员所在的偏移量。

样本:

struct abc1 { int a, b, c; };
union abc2 { int a, b, c; };
struct abc3 { abc3() { } int a, b, c; }; // non-POD
union abc4 { abc4() { } int a, b, c; };  // non-POD

assert(offsetof(abc1, a) == 0); // always, because there's no padding before a.
assert(offsetof(abc1, b) == 4); // here, on my system
assert(offsetof(abc2, a) == offsetof(abc2, b)); // (members overlap)
assert(offsetof(abc3, c) == 8); // undefined behavior. GCC outputs warnings
assert(offsetof(abc4, a) == 0); // undefined behavior. GCC outputs warnings

@Jonathan提供了一个很好的示例,说明可以在哪里使用它。我记得曾经见过它用于实现侵入式列表(其数据项包括next和prev指针本身的列表),但是令人遗憾的是,我不记得它在哪里对实现它有所帮助。

10-04 14:23