C ++ offsetof char *算术 [英] C++ offsetof char* arithmetic
问题描述
在此答案中,int8_t*
用于(字节)指针算术:
In this answer, int8_t*
is used for (byte) pointer arithmetic:
std::size_t offset = offsetof(Thing, b);
Thing* thing = reinterpret_cast<Thing*>(reinterpret_cast<int8_t*>(ptr) - offset);
过去我一直使用char*
,但是评论确实令人困惑,没有人回应,所以我发布了这个单独的问题.
I've always used char*
in the past but the comments are really confusing, and nobody responded, so I posted this separate question.
char*
是否有效,并且是进行这些计算的首选方式?
Is char*
valid, and the preferred way of doing these calculations?
推荐答案
您必须使用char*
:将reinterpret_cast
与int8_t*
一起使用的行为指向指向以下内容的指针不是char*
可以视为规则的例外.
You must use char*
: the behaviour on using a reinterpret_cast
with int8_t*
on a pointer to something that is not an int8_t
is undefined. Casting to char*
can be viewed as an exception to the rule.
Pre C ++ 14,char
可以是-127到+127的1's补码类型. int8_t
必须为2的补码.即使是C ++ 14及更高版本,我也看不到为什么类型相关:char
仍然可以是有符号或无符号类型.
Pre C++14, char
can be a 1's complement type with range -127 to +127. int8_t
must be 2's complement. Even C++14 and onwards, I can't see why the types are related: char
can still be either a signed or an unsigned type.
这篇关于C ++ offsetof char *算术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!