关于 [expr.static.cast]/13 的困惑

Confusion about [expr.static.cast]/13

我无法理解引用(具体来说,粗体部分):

A prvalue of type “pointer to cv1 void” can be converted to a prvalue of type “pointer to cv2 T”, where T is an object type and cv2 is the same cv-qualification as, or greater cv-qualification than, cv1. If the original pointer value represents the address A of a byte in memory and A does not satisfy the alignment requirement of T, then the resulting pointer value is unspecified.

int i = 0;
void *vp = &i;
auto *res = static_cast<double*>(vp);

我的问题是:

does the address pointed by res (address of int) satisfy the alignment requirement of double?

这取决于实施。很可能没有。通常 int 的对齐要求小于 double.

的对齐要求

例如,在 x86-64 系统上使用的 V ABI 例如在 Linux 上,int 有对齐要求 4double8.

您可以检查是否满足对齐要求,例如使用以下 static_assert:

static_assert(alignof(int) >= alignof(double));

does the resulting pointer res has an unspecified value?

如果未满足对齐要求(即 static_assert 失败),是的。否则它将指向对象 i.

And when I have something like this: static_cast<double*>(static_cast<void *>(&i))

这与代码段中显示的内容完全相同。


请注意,即使满足对齐要求,res 也不能用于访问它指向的对象的值,因为那样会违反指针别名规则。所以转换的结果很可能对任何东西都没有用。