C++ offsetof char* arithmetic

删除回忆录丶 提交于 2019-12-12 10:32:33

问题


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);

I've always used char* in the past but the comments are really confusing, and nobody responded, so I posted this separate question.

Is char* valid, and the preferred way of doing these calculations?


回答1:


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 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.



来源:https://stackoverflow.com/questions/33872140/c-offsetof-char-arithmetic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!