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.n
的访问权限通过 reinterpret_cast<A*>(reinterpret_cast<double(*)[4]>(p - 1))->n
.如果内部转换成功产生指向 a.x
的指针, 然后外部转换将产生指向 a
的指针,给类成员访问定义的行为,从而禁止优化。
关于c++ - 指针互换性与具有相同地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47926463/