reinterpret_cast 和显式对齐要求

reinterpret_cast and explicit alignment requirement

考虑到关于 reinterpret_cast 的这个(粗体部分),我期望下面的代码片段在将 X* 转换为 Y* 时会生成不同的地址,因为后者更严格比前者对齐。我在这里错过了什么?

Any object pointer type T1* can be converted to another object pointer type cv T2*. This is exactly equivalent to static_cast<cv T2*>(static_cast<cv void*>(expression)) (which implies that if T2's alignment requirement is not stricter than T1's, the value of the pointer does not change and conversion of the resulting pointer back to its original type yields the original value)

cppreference/reinterpret_cast

#include <iostream>


struct alignas (1) X
{
    char c;
};


struct  alignas (32) Y
{
    char c;
};

int main(int argc, const char *const* const argv)
{
    std::cout << alignof(X) << " " << alignof(Y) << std::endl;

    X x;
    Y y;
    std::cout << &x << " " << reinterpret_cast<Y*>(&x) << std::endl;
    std::cout << &y << " " << reinterpret_cast<X*>(&y) << std::endl;

}

输出

Program returned: 0
1 32
0x7ffef3434578 0x7ffef3434578
0x7ffef3434540 0x7ffef3434540

snippet on godbolt

引用自[expr.reinterpret.cast]/7

An object pointer can be explicitly converted to an object pointer of a different type. When a prvalue v of object pointer type is converted to the object pointer type “pointer to cv T”, the result is static_­cast<cv T*>(static_­cast<cv void*>(v)).

然后,来自[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....

我相信这些规则在这里适用。在您的例子中,reinterpret_cast<Y*>(&x) 被解析为 static_cast<Y*>(static_cast<void*>(&x))原始指针值 static_cast<void*>(&x)表示地址A,这个地址一般不满足Y的对齐要求。 因此,结果指针的值为未指定