gpt4 book ai didi

c++ - 你能对指向另一个对象的 char* 进行算术运算吗

转载 作者:可可西里 更新时间:2023-11-01 18:39:24 24 4
gpt4 key购买 nike

<分区>

这是读取普通可复制对象字节的常用方法

Object obj;
auto p = reinterpret_cast<char*>(&obj);
for(size_t i = 0; i < sizeof(obj); i++)
consume(p[i]);

问题不在于严格别名,char* 可以为任何东西起别名。问题出在 [expr.add] 的这段话中

When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the expression P points to element x[i] of an array object x with n elements, the expressions P + J and J + P (where J has the value j) point to the (possibly-hypothetical) element x[i + j] if 0 ≤ i + j ≤ n; otherwise, the behavior is undefined. Likewise, the expression P - J points to the (possibly-hypothetical) element x[i − j] if 0 ≤ i − j ≤ n; otherwise, the behavior is undefined.

假设元素指代

A pointer past the last element of an array x of n elements is considered to be equivalent to a pointer to a hypothetical element x[n] for this purpose

也就是说,只有在指向数组的指针上运算,并且结果还在其范围内时,运算才是合法的。

但是,这里明明没有char[sizeof(Object)],我们可以对那个指针做运算吗?

请注意,读取对象字节的合法解决方案是 std::memcpy 对象。但如果那是唯一的解决方案,它会问,如果您几乎无法用它做任何事情,为什么还要允许 char* 别名?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com