gpt4 book ai didi

c++ - 指针互转换与具有相同地址

转载 作者:IT老高 更新时间:2023-10-28 21:35:56 30 4
gpt4 key购买 nike

working draft of the standard N4659说:

[basic.compound]
If two objects are pointer-interconvertible, then they have the same address

然后注意到

An array object and its first element are not pointer-interconvertible, even though they have the same address

使数组对象及其第一个元素不可指针互转换的基本原理是什么?更一般地说,区分指针互转换概念和具有相同地址的概念的基本原理是什么?是不是哪里有矛盾?

看起来,给定这个语句序列

int a[10];

void* p1 = static_cast<void*>(&a[0]);
void* p2 = static_cast<void*>(&a);

int* i1 = static_cast<int*>(p1);
int* i2 = static_cast<int*>(p2);

我们有 p1 == p2,但是,i1 定义明确,使用 i2 会导致 UB。

最佳答案

显然存在基于此优化的现有实现。考虑:

struct A {
double x[4];
int n;
};

void g(double* p);

int f() {
A a { {}, 42 };
g(&a.x[1]);
return a.n; // optimized to return 42;
// valid only if you can't validly obtain &a.n from &a.x[1]
}

给定 p = &a.x[1]; , g可能会尝试访问 a.nreinterpret_cast<A*>(reinterpret_cast<double(*)[4]>(p - 1))->n .如果内部转换成功产生了指向 a.x 的指针,那么外部转换将产生一个指向 a 的指针,给类成员访问定义的行为,从而禁止优化。

关于c++ - 指针互转换与具有相同地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47924103/

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