无法理解宏定义(将常数编号转换为类指针)

时间:2016-06-11 06:39:42

标签: c++ macros

在代码中,我看到下面定义的宏,我无法理解。

#define OFFSET_OF_FIELD_(f) (reinterpret_cast<char*>(      \
  &reinterpret_cast<NetParameter*>(16)->f) - \
   reinterpret_cast<char*>(16))

宏名称似乎是计算类结构中字段f的偏移量。它具有从字段地址中减去起始地址的形式。 16号怎么用?和deosn的reinterpret_case仅适用于16?(而不是16 - > f)。 如果有人请向我解释这段代码,我将不胜感激。

1 个答案:

答案 0 :(得分:3)

(现已重构的)protobuf标题(链接here)中的注释解释了

// Note that we calculate relative to the pointer value 16 here since if we
// just use zero, GCC complains about dereferencing a NULL pointer.  We
// choose 16 rather than some other number just in case the compiler would
// be confused by an unaligned pointer.
#define GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TYPE, FIELD)    \
  static_cast<int>(                                           \
      reinterpret_cast<const char*>(                          \
          &reinterpret_cast<const TYPE*>(16)->FIELD) -        \
      reinterpret_cast<const char*>(16))
#endif

因此使用16的原因有两个:

  • 避免使用NULL指针
  • 使用对齐指针

请注意,这是known to create some issues(可能会被支持的__builtin_offsetof取代。)