【发布时间】:2017-10-13 21:49:52
【问题描述】:
让我们考虑一下这段代码:
int i;
int is[10]{};
unsigned char * p = reinterpret_cast<unsigned char*>(&i);
//p defined to point to the object-representation of the first element of array ints
unsigned char * ps = reinterpret_cast<unsigned char*>(&is[0]);
p += sizeof(int);
ps += sizeof(int);
//now ps points to the end of ints[0] and p point to the end of i;
p += sizeof(int); //Undefined behavior according to [expr.add]
ps += sizeof(int); //Undefined behavior?
unsigned char c = *ps;//Undefined behavior?
如果我们认为ps 指向is[0] 的object-representation,那么根据指针运算规则,最后两行代码的行为是未定义的。
不过,如果 ps 也是一个指向 int is 数组的object-representation 的指针,则定义了行为。
所以我的问题是:指向suboject 的object-representation 的指针是否也是指向包含的object-representation 元素的指针完整的对象?
【问题讨论】:
-
我认为您将“子对象”与“数组成员”混淆了。对于成员子对象,允许在同一个大对象内的指针之间进行比较,但不允许进行算术运算。对于指向数组元素的指针,可以使用指针算法。
-
@BenVoigt 如果您点击链接“suboject”,您将获得:“子对象可以是成员子对象([class.mem]),基类子对象([class.derived]),或数组元素”。
-
您是在问是否对字符类型使用
offsetof和指针算法进行了明确定义? -
@BenVoigt 我确实知道指针算术的规则。这里的问题是关于对象表示的指针算法
-
@RichardCritten 我对此表示怀疑,但显然,对象表示的概念与存储的概念紧密耦合。这是我问的问题,原因是我对 cmets 有疑问,我的问题实际上是指针值是否有效?显然是的。 stackoverflow.com/questions/46735324/…
标签: c++ language-lawyer pointer-arithmetic