指针相互转换与具有相同地址 [英] Pointer interconvertibility vs having the same address
问题描述
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
使数组对象及其第一个元素不可相互转换的基本原理是什么?更一般地说,将指针可相互转换的概念与具有相同地址的概念区分开来的基本原理是什么?是不是哪里有什么矛盾?
What is the rationale for making an array object and its first element non-pointer-interconvertible? More generally, what is the rationale for distinguishing the notion of pointer-interconvertibility from the notion of having the same address? Isn't there a contradiction in there somewhere?
似乎给定了这个语句序列
It would appear that given this sequence of statements
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.
we have p1 == p2
, however, i1
is well defined and using i2
would result in UB.
推荐答案
显然存在基于此优化的实现.考虑:
There are apparently existing implementations that optimize based on this. Consider:
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 = &ax[1];
,g
可能会尝试通过 reinterpret_castan
的访问*>(reinterpret_castax
的指针,那么外部强制转换将生成一个指向 a
的指针,让类成员访问定义的行为,从而禁止优化.
Given p = &a.x[1];
, g
might attempt to obtain access to a.n
by reinterpret_cast<A*>(reinterpret_cast<double(*)[4]>(p - 1))->n
. If the inner cast successfully yielded a pointer to a.x
, then the outer cast will yield a pointer to a
, giving the class member access defined behavior and thus outlawing the optimization.
这篇关于指针相互转换与具有相同地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!