无法理解宏定义(将常量数强制转换为类指针)
can't understand a macro definition (casting constant number to a class pointer)
在代码中,我看到下面定义的宏,我无法理解。
#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)。如果有人请向我解释此代码,我将不胜感激。
(现已重构)protobuf 标头中的注释(此处链接)对此进行了解释
// 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 指针
- 使用对齐的指针
请注意,已知这会产生一些问题(如果支持,可能会替换为__builtin_offsetof
)。
相关文章:
- 转换指针引用的字符串
- 无法向上转换指针到指针参数
- 混合转换指针和引用
- 堆栈对象的强制转换指针
- 基类到派生模板类的强制转换指针,而不知道类型
- 删除类型转换指针的最佳方法
- 管理到本机值类转换:强制转换指针是否安全?
- 转换指针类型
- 为什么函数不能正确强制转换指针(从基类到派生类)
- 当我们递增下面的类型转换指针时会发生什么?
- 类型强制转换指针构造函数调用
- 如何转换(指针向量)-->(指向指针数组的指针)
- 如何从类功能转换指针
- 在C++对象中:我应该使用父类强制转换指针,还是应该使用实际类本身进行强制转换
- Delphi中的类型转换指针添加
- C++分段错误(核心转储)错误 - 强制转换指针/将函数值返回到线程
- 以C++和运算符优先级键入指向数组成员的强制转换指针
- C++动态强制转换指针的内存清理
- 转换指针和引用的好处
- 在c++中转换指针