gpt4 book ai didi

c++ - 安全派生指针值的示例

转载 作者:太空狗 更新时间:2023-10-29 21:42:44 24 4
gpt4 key购买 nike

我正在使用 N3797 工作草案。

第 5.7/1 节说:

[...] For addition, either both operands shall have arithmetic or unscoped enumeration type, or one operand shall be a pointer to a completely-defined object type and the other shall have integral or unscoped enumeration type.

好的。但是请考虑 3.7.4.3/3 节中的规则:

— the result of an additive or bitwise operation, one of whose operands is an integer representation of a safely-derived pointer value P, if that result converted by reinterpret_cast<void*> would compare equal to a safely-derived pointer computable from reinterpret_cast<void*>(P).

也就是说,我们不能对指向void 的指针应用指针算法。 .您能否提供一个反射(reflect) 3.7.4.3 规则的示例?

类似的question没有提供合适的示例,因为指向 void 算术的指针出现在这里。

最佳答案

3.7.4.3/3 所说的全部内容是,如果您有一个“安全派生指针的整数表示”,并用它做数学运算,结果只是一个有效的“安全派生指针的整数表示”,如果单独使用指针运算和强制转换可能会得出相同的结果。

尽管不允许对void* 进行算术运算directy,还有多种其他方法可以从 void* 获取有效指针.虽然我懒得用标准的引号来支持每一步,但下面的例子应该是有效的:

double arr[10];
double* P = &arr[0]; // safely derived pointer
intptr_t N = reinterpret_cast<intptr_t>(P); // valid integer repr

void* V = reinterpret_cast<void*>(P);

// Compute &a[1] from V
void* V2 = reinterpret_cast<void*>(
static_cast<char*>(V) + sizeof(double));

// Do the same with N
intptr_t N2 = N + sizeof(double);

assert(reinterpret_cast<void*>(N2) == V2);
  • V2 是可从reinterpret_cast<void*>(P) 计算的安全派生指针
  • N2 是加法或按位运算的结果,其中一个操作数 (N) 是安全派生的指针值 P 的整数表示

由于 V2 和 N2 比较相等,因此 N2 也是“安全派生指针的整数表示”。

关于c++ - 安全派生指针值的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25216568/

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